258 $this->mMainModule = $mainModule;
259 $this->mModuleName = $moduleName;
260 $this->mModulePrefix = $modulePrefix;
329 if ( !is_array( $examples ) ) {
330 $examples = [ $examples ];
331 } elseif ( $examples && ( count( $examples ) & 1 ) == 0 &&
332 array_keys( $examples ) === range( 0, count( $examples ) - 1 ) &&
333 !preg_match(
'/^\s*api\.php\?/', $examples[0] )
338 $examplesCount = count( $examples );
339 for ( $i = 0; $i < $examplesCount; $i += 2 ) {
340 $tmp[$examples[$i + 1]] = $examples[$i];
345 foreach ( $examples as $k => $v ) {
346 if ( is_numeric( $k ) ) {
352 if ( is_array( $msg ) ) {
353 $msg = implode(
' ', $msg );
357 $qs = preg_replace(
'/^\s*api\.php\?/',
'', $qs );
358 $ret[$qs] = $this->
msg(
'api-help-fallback-example', [ $msg ] );
564 self::dieDebug( __METHOD__,
'base method was called on main module.' );
567 return $this->
getMain()->lacksSameOriginSecurity();
596 if ( $path ===
'main' ) {
600 $parts = explode(
'+', $path );
601 if ( count( $parts ) === 1 ) {
603 $parts = explode(
' ', $path );
606 $count = count( $parts );
607 for ( $i = 0; $i < $count; $i++ ) {
609 $manager = $parent->getModuleManager();
610 if ( $manager ===
null ) {
611 $errorPath = implode(
'+', array_slice( $parts, 0, $i ) );
612 $this->
dieWithError( [
'apierror-badmodule-nosubmodules', $errorPath ],
'badmodule' );
614 $module = $manager->getModule( $parts[$i] );
616 if ( $module ===
null ) {
617 $errorPath = $i ? implode(
'+', array_slice( $parts, 0, $i ) ) : $parent->getModuleName();
619 [
'apierror-badmodule-badsubmodule', $errorPath,
wfEscapeWikiText( $parts[$i] ) ],
636 self::dieDebug( __METHOD__,
'base method was called on main module. ' );
639 return $this->
getMain()->getResult();
650 self::dieDebug( __METHOD__,
'base method was called on main module. ' );
653 return $this->
getMain()->getErrorFormatter();
661 if ( !isset( $this->mSlaveDB ) ) {
676 self::dieDebug( __METHOD__,
'base method was called on main module. ' );
679 return $this->
getMain()->getContinuationManager();
690 self::dieDebug( __METHOD__,
'base method was called on main module. ' );
693 $this->
getMain()->setContinuationManager( $manager );
722 if ( is_array( $paramName ) ) {
723 return array_map(
function ( $name ) {
724 return $this->mModulePrefix .
$name;
727 return $this->mModulePrefix . $paramName;
742 if ( !isset( $this->mParamCache[$parseLimit] ) ) {
747 foreach (
$params as $paramName => $paramSettings ) {
749 $paramName, $paramSettings, $parseLimit );
752 $this->mParamCache[$parseLimit] = $results;
755 return $this->mParamCache[$parseLimit];
777 $required = func_get_args();
778 array_shift( $required );
780 $intersection = array_intersect( array_keys( array_filter(
$params,
781 [ $this,
'parameterNotEmpty' ] ) ), $required );
783 if ( count( $intersection ) > 1 ) {
785 'apierror-invalidparammix',
786 Message::listParam( array_map(
790 array_values( $intersection )
792 count( $intersection ),
794 } elseif ( count( $intersection ) == 0 ) {
796 'apierror-missingparam-one-of',
797 Message::listParam( array_map(
801 array_values( $required )
815 $required = func_get_args();
816 array_shift( $required );
818 $intersection = array_intersect( array_keys( array_filter(
$params,
819 [ $this,
'parameterNotEmpty' ] ) ), $required );
821 if ( count( $intersection ) > 1 ) {
823 'apierror-invalidparammix',
824 Message::listParam( array_map(
828 array_values( $intersection )
830 count( $intersection ),
843 $required = func_get_args();
844 array_shift( $required );
846 $intersection = array_intersect(
847 array_keys( array_filter(
$params, [ $this,
'parameterNotEmpty' ] ) ),
851 if ( count( $intersection ) == 0 ) {
853 'apierror-missingparam-at-least-one-of',
854 Message::listParam( array_map(
858 array_values( $required )
874 if ( $this->
getConfig()->
get(
'DebugAPI' ) || $this->
getMain()->isInternalMode() ) {
878 $queryValues = $this->
getRequest()->getQueryValues();
880 foreach (
$params as $param ) {
881 if ( $prefix !==
'noprefix' ) {
884 if ( array_key_exists( $param, $queryValues ) ) {
885 $badParams[] = $param;
891 [
'apierror-mustpostparams', join(
', ', $badParams ), count( $badParams ) ]
903 return !is_null( $x ) && $x !==
false;
921 if ( isset(
$params[
'title'] ) ) {
922 $titleObj = Title::newFromText(
$params[
'title'] );
923 if ( !$titleObj || $titleObj->isExternal() ) {
926 if ( !$titleObj->canExist() ) {
930 if ( $load !==
false ) {
931 $pageObj->loadPageData( $load );
933 } elseif ( isset(
$params[
'pageid'] ) ) {
934 if ( $load ===
false ) {
958 if ( isset(
$params[
'title'] ) ) {
959 $titleObj = Title::newFromText(
$params[
'title'] );
960 if ( !$titleObj || $titleObj->isExternal() ) {
964 } elseif ( isset(
$params[
'pageid'] ) ) {
965 $titleObj = Title::newFromID(
$params[
'pageid'] );
983 $userWatching = $this->
getUser()->isWatched( $titleObj, User::IGNORE_USER_RIGHTS );
985 switch ( $watchlist ) {
993 # If the user is already watching, don't bother checking
994 if ( $userWatching ) {
997 # If no user option was passed, use watchdefault and watchcreations
998 if ( is_null( $userOption ) ) {
999 return $this->
getUser()->getBoolOption(
'watchdefault' ) ||
1000 $this->
getUser()->getBoolOption(
'watchcreations' ) && !$titleObj->exists();
1003 # Watch the article based on the user preference
1004 return $this->
getUser()->getBoolOption( $userOption );
1007 return $userWatching;
1010 return $userWatching;
1028 if ( !is_array( $paramSettings ) ) {
1030 self::PARAM_DFLT => $paramSettings,
1034 $default = isset( $paramSettings[self::PARAM_DFLT] )
1037 $multi = isset( $paramSettings[self::PARAM_ISMULTI] )
1040 $multiLimit1 = isset( $paramSettings[self::PARAM_ISMULTI_LIMIT1] )
1043 $multiLimit2 = isset( $paramSettings[self::PARAM_ISMULTI_LIMIT2] )
1046 $type = isset( $paramSettings[self::PARAM_TYPE] )
1049 $dupes = isset( $paramSettings[self::PARAM_ALLOW_DUPLICATES] )
1052 $deprecated = isset( $paramSettings[self::PARAM_DEPRECATED] )
1055 $deprecatedValues = isset( $paramSettings[self::PARAM_DEPRECATED_VALUES] )
1058 $required = isset( $paramSettings[self::PARAM_REQUIRED] )
1061 $allowAll = isset( $paramSettings[self::PARAM_ALL] )
1066 if ( !isset(
$type ) ) {
1067 if ( isset( $default ) ) {
1068 $type = gettype( $default );
1074 if (
$type ==
'password' || !empty( $paramSettings[self::PARAM_SENSITIVE] ) ) {
1075 $this->
getMain()->markParamsSensitive( $encParamName );
1078 if (
$type ==
'boolean' ) {
1079 if ( isset( $default ) && $default !==
false ) {
1083 "Boolean param $encParamName's default is set to '$default'. " .
1084 'Boolean parameters must default to false.'
1089 } elseif (
$type ==
'upload' ) {
1090 if ( isset( $default ) ) {
1094 "File upload param $encParamName's default is set to " .
1095 "'$default'. File upload parameters may not have a default." );
1098 self::dieDebug( __METHOD__,
"Multi-values not supported for $encParamName" );
1101 if ( !
$value->exists() ) {
1105 $value = $this->
getMain()->getRequest()->unsetVal( $encParamName );
1108 [
'apierror-badupload', $encParamName ],
1109 "badupload_{$encParamName}"
1114 $value = $this->
getMain()->getVal( $encParamName, $default );
1117 $type = MWNamespace::getValidNamespaces();
1118 if ( isset( $paramSettings[self::PARAM_EXTRA_NAMESPACES] ) &&
1119 is_array( $paramSettings[self::PARAM_EXTRA_NAMESPACES] )
1121 $type = array_merge(
$type, $paramSettings[self::PARAM_EXTRA_NAMESPACES] );
1128 if ( isset( $paramSettings[self::PARAM_SUBMODULE_MAP] ) ) {
1129 $type = array_keys( $paramSettings[self::PARAM_SUBMODULE_MAP] );
1136 $rawValue =
$request->getRawVal( $encParamName );
1137 if ( $rawValue ===
null ) {
1138 $rawValue = $default;
1142 if ( isset(
$value ) && substr( $rawValue, 0, 1 ) ===
"\x1f" ) {
1146 $value = join(
"\x1f",
$request->normalizeUnicode( explode(
"\x1f", $rawValue ) ) );
1148 $this->
dieWithError(
'apierror-badvalue-notmultivalue',
'badvalue_notmultivalue' );
1153 if ( $rawValue !==
$value ) {
1159 if ( $allowAll && $multi && is_array(
$type ) && in_array( $allSpecifier,
$type,
true ) ) {
1162 "For param $encParamName, PARAM_ALL collides with a possible value" );
1164 if ( isset(
$value ) && ( $multi || is_array(
$type ) ) ) {
1170 $allowAll ? $allSpecifier :
null,
1179 if ( !is_array(
$type ) ) {
1186 if ( $required &&
$value ===
'' ) {
1187 $this->
dieWithError( [
'apierror-missingparam', $paramName ] );
1191 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[
self::PARAM_MIN] :
null;
1192 $max = isset( $paramSettings[self::PARAM_MAX] ) ? $paramSettings[
self::PARAM_MAX] :
null;
1193 $enforceLimits = isset( $paramSettings[self::PARAM_RANGE_ENFORCE] )
1196 if ( is_array(
$value ) ) {
1198 if ( !is_null( $min ) || !is_null( $max ) ) {
1199 foreach (
$value as &$v ) {
1200 $this->
validateLimit( $paramName, $v, $min, $max,
null, $enforceLimits );
1205 if ( !is_null( $min ) || !is_null( $max ) ) {
1211 if ( !$parseLimit ) {
1215 if ( !isset( $paramSettings[self::PARAM_MAX] )
1216 || !isset( $paramSettings[self::PARAM_MAX2] )
1220 "MAX1 or MAX2 are not defined for the limit $encParamName"
1224 self::dieDebug( __METHOD__,
"Multi-values not supported for $encParamName" );
1226 $min = isset( $paramSettings[self::PARAM_MIN] ) ? $paramSettings[
self::PARAM_MIN] : 0;
1238 $paramSettings[self::PARAM_MAX],
1239 $paramSettings[self::PARAM_MAX2]
1245 self::dieDebug( __METHOD__,
"Multi-values not supported for $encParamName" );
1249 if ( is_array(
$value ) ) {
1250 foreach (
$value as $key => $val ) {
1258 if ( is_array(
$value ) ) {
1259 foreach (
$value as $key => $val ) {
1270 if ( !is_array(
$value ) && !$multi ) {
1274 if ( !$tagsStatus->isGood() ) {
1279 self::dieDebug( __METHOD__,
"Param $encParamName's type is unknown - $type" );
1284 if ( !$dupes && is_array(
$value ) ) {
1289 if ( $deprecated &&
$value !==
false ) {
1290 $feature = $encParamName;
1292 while ( !$m->isMain() ) {
1293 $p = $m->getParent();
1294 $name = $m->getModuleName();
1295 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1296 $feature =
"{$param}={$name}&{$feature}";
1299 $this->
addDeprecation( [
'apiwarn-deprecation-parameter', $encParamName ], $feature );
1303 $usedDeprecatedValues = $deprecatedValues &&
$value !==
false
1304 ? array_intersect( array_keys( $deprecatedValues ), (array)
$value )
1306 if ( $usedDeprecatedValues ) {
1307 $feature =
"$encParamName=";
1309 while ( !$m->isMain() ) {
1310 $p = $m->getParent();
1311 $name = $m->getModuleName();
1312 $param = $p->encodeParamName( $p->getModuleManager()->getModuleGroup( $name ) );
1313 $feature =
"{$param}={$name}&{$feature}";
1316 foreach ( $usedDeprecatedValues as $v ) {
1317 $msg = $deprecatedValues[$v];
1318 if ( $msg ===
true ) {
1319 $msg = [
'apiwarn-deprecation-parameter',
"$encParamName=$v" ];
1324 } elseif ( $required ) {
1325 $this->
dieWithError( [
'apierror-missingparam', $paramName ] );
1340 $this->
addWarning( [
'apiwarn-badutf8', $encParamName ] );
1351 if ( substr(
$value, 0, 1 ) ===
"\x1f" ) {
1358 return explode( $sep,
$value, $limit );
1379 $allSpecifier =
null, $limit1 =
null, $limit2 =
null
1381 if ( ( trim(
$value ) ===
'' || trim(
$value ) ===
"\x1f" ) && $allowMultiple ) {
1390 $sizeLimit = count( $valuesList ) > $limit1 && $this->mMainModule->canApiHighLimits()
1394 if ( $allowMultiple && is_array( $allowedValues ) && $allSpecifier &&
1395 count( $valuesList ) === 1 && $valuesList[0] === $allSpecifier
1397 return $allowedValues;
1400 if ( self::truncateArray( $valuesList, $sizeLimit ) ) {
1402 [
'apiwarn-toomanyvalues', $valueName, $sizeLimit ],
1403 "too-many-$valueName-for-{$this->getModulePath()}"
1407 if ( !$allowMultiple && count( $valuesList ) != 1 ) {
1409 if ( in_array(
$value, $allowedValues,
true ) ) {
1413 if ( is_array( $allowedValues ) ) {
1414 $values = array_map(
function ( $v ) {
1416 }, $allowedValues );
1418 'apierror-multival-only-one-of',
1420 Message::listParam( $values ),
1422 ],
"multival_$valueName" );
1425 'apierror-multival-only-one',
1427 ],
"multival_$valueName" );
1431 if ( is_array( $allowedValues ) ) {
1433 $unknown = array_map(
'wfEscapeWikiText', array_diff( $valuesList, $allowedValues ) );
1434 if ( count( $unknown ) ) {
1435 if ( $allowMultiple ) {
1437 'apiwarn-unrecognizedvalues',
1439 Message::listParam( $unknown,
'comma' ),
1444 [
'apierror-unrecognizedvalue', $valueName,
wfEscapeWikiText( $valuesList[0] ) ],
1445 "unknown_$valueName"
1450 $valuesList = array_intersect( $valuesList, $allowedValues );
1453 return $allowMultiple ? $valuesList : $valuesList[0];
1467 $enforceLimits =
false
1469 if ( !is_null( $min ) &&
$value < $min ) {
1471 [
'apierror-integeroutofrange-belowminimum',
1473 'integeroutofrange',
1474 [
'min' => $min,
'max' => $max,
'botMax' => $botMax ?: $max ]
1476 $this->
warnOrDie( $msg, $enforceLimits );
1482 if ( $this->
getMain()->isInternalMode() ) {
1488 if ( !is_null( $max ) &&
$value > $max ) {
1489 if ( !is_null( $botMax ) && $this->
getMain()->canApiHighLimits() ) {
1490 if (
$value > $botMax ) {
1492 [
'apierror-integeroutofrange-abovebotmax',
1494 'integeroutofrange',
1495 [
'min' => $min,
'max' => $max,
'botMax' => $botMax ?: $max ]
1497 $this->
warnOrDie( $msg, $enforceLimits );
1502 [
'apierror-integeroutofrange-abovemax',
1504 'integeroutofrange',
1505 [
'min' => $min,
'max' => $max,
'botMax' => $botMax ?: $max ]
1507 $this->
warnOrDie( $msg, $enforceLimits );
1526 'unclear-"now"-timestamp'
1532 if (
$value ===
'now' ) {
1537 if ( $unixTimestamp ===
false ) {
1540 "badtimestamp_{$encParamName}"
1559 if ( !isset( $salts[$tokenType] ) ) {
1561 "Module '{$this->getModuleName()}' tried to use token type '$tokenType' " .
1562 'without registering it'
1569 if ( $tokenObj->match( $token ) ) {
1574 if ( $webUiSalt !==
null && $this->
getUser()->matchEditToken(
1592 $title = Title::makeTitleSafe( NS_USER,
$value );
1593 if ( $title ===
null || $title->hasFragment() ) {
1596 "baduser_{$encParamName}"
1600 return $title->getText();
1616 protected function setWatch( $watch, $titleObj, $userOption =
null ) {
1633 while ( count( $arr ) > $limit ) {
1648 if ( !is_null(
$params[
'owner'] ) && !is_null(
$params[
'token'] ) ) {
1649 $user = User::newFromName(
$params[
'owner'],
false );
1650 if ( !( $user && $user->getId() ) ) {
1655 $token = $user->getOption(
'watchlisttoken' );
1656 if ( $token ==
'' || !hash_equals( $token,
$params[
'token'] ) ) {
1657 $this->
dieWithError(
'apierror-bad-watchlist-token',
'bad_wltoken' );
1660 if ( !$this->
getUser()->isLoggedIn() ) {
1661 $this->
dieWithError(
'watchlistanontext',
'notloggedin' );
1678 if ( is_array( $v ) ) {
1679 return array_map(
'self::escapeWikiText', $v );
1682 '__' =>
'__',
'{' =>
'{',
'}' =>
'}',
1683 '[[Category:' =>
'[[:Category:',
1684 '[[File:' =>
'[[:File:',
'[[Image:' =>
'[[:Image:',
1702 if ( is_string( $msg ) ) {
1704 } elseif ( is_array( $msg ) ) {
1705 $msg = call_user_func_array(
'wfMessage', $msg );
1707 if ( !$msg instanceof
Message ) {
1727 if ( $user ===
null ) {
1732 foreach ( $errors as $error ) {
1733 if ( is_array( $error ) && $error[0] ===
'blockedtext' && $user->getBlock() ) {
1739 } elseif ( is_array( $error ) && $error[0] ===
'autoblockedtext' && $user->getBlock() ) {
1741 'apierror-autoblocked',
1745 } elseif ( is_array( $error ) && $error[0] ===
'systemblockedtext' && $user->getBlock() ) {
1747 'apierror-systemblocked',
1752 call_user_func_array( [
$status,
'fatal' ], (array)$error );
1794 $data = (
array)$data;
1795 if ( $feature !==
null ) {
1796 $data[
'feature'] = $feature;
1799 $this->
addWarning( $msg,
'deprecation', $data );
1803 $msgs = [ $this->
msg(
'api-usage-mailinglist-ref' ) ];
1804 Hooks::run(
'ApiDeprecationHelp', [ &$msgs ] );
1805 if ( count( $msgs ) > 1 ) {
1806 $key =
'$' . join(
' $', range( 1, count( $msgs ) ) );
1807 $msg = (
new RawMessage( $key ) )->params( $msgs );
1809 $msg = reset( $msgs );
1811 $this->
getMain()->addWarning( $msg,
'deprecation-help' );
1880 if ( $enforceLimits ) {
1899 'apierror-autoblocked',
1922 throw new MWException(
'Successful status passed to ApiBase::dieStatus' );
1928 if ( !
$status->getErrorsByType(
'error' ) ) {
1929 $newStatus = Status::newGood();
1930 foreach (
$status->getErrorsByType(
'warning' ) as $err ) {
1931 call_user_func_array(
1932 [ $newStatus,
'fatal' ],
1933 array_merge( [ $err[
'message'] ], $err[
'params'] )
1936 if ( !$newStatus->getErrorsByType(
'error' ) ) {
1937 $newStatus->fatal(
'unknownerror-nocode' );
1952 'apierror-readonly',
1970 $rights = (
array)$rights;
1971 if ( !call_user_func_array( [ $user,
'isAllowedAny' ], $rights ) ) {
1972 $this->
dieWithError( [
'apierror-permissiondenied', $this->
msg(
"action-{$rights[0]}" ) ] );
1990 foreach ( (array)$actions as $action ) {
1991 $errors = array_merge( $errors, $title->getUserPermissionsErrors( $action, $user ) );
2010 if ( $this->
getConfig()->
get(
'DebugAPI' ) !==
true ) {
2038 protected static function dieDebug( $method, $message ) {
2039 throw new MWException(
"Internal error in $method: $message" );
2050 $s =
'"' . addslashes( $feature ) .
'"' .
2053 ' "' . addslashes(
$request->getHeader(
'Referer' ) ) .
'"' .
2054 ' "' . addslashes( $this->
getMain()->getUserAgent() ) .
'"';
2075 return "apihelp-{$this->getModulePath()}-summary";
2089 "apihelp-{$this->getModulePath()}-extended-description",
2090 'api-help-no-extended-description',
2110 if ( !$msg->exists() ) {
2111 wfDeprecated(
'API help "description" messages',
'1.30' );
2118 preg_replace(
'/\n.*/s',
'', $msg->text() )
2136 Hooks::run(
'APIGetDescription', [ &$apiModule, &$desc ] );
2138 if ( is_array( $desc ) ) {
2139 $desc = implode(
"\n", $desc );
2157 if ( $summary->exists() ) {
2158 $msgs = [ $summary, $extendedDescription ];
2160 wfDeprecated(
'API help "description" messages',
'1.30' );
2166 if ( !$description->exists() ) {
2167 $description = $this->
msg(
'api-help-fallback-description', $desc );
2169 $msgs = [ $description ];
2172 Hooks::run(
'APIGetDescriptionMessages', [ $this, &$msgs ] );
2193 self::PARAM_TYPE =>
'string',
2194 self::PARAM_REQUIRED =>
true,
2195 self::PARAM_SENSITIVE =>
true,
2196 self::PARAM_HELP_MSG => [
2197 'api-help-param-token',
2205 Hooks::run(
'APIGetAllowedParams', [ &$apiModule, &
$params,
$flags ] );
2226 Hooks::run(
'APIGetParamDescription', [ &$apiModule, &$desc ] );
2235 foreach (
$params as $param => $settings ) {
2236 if ( !is_array( $settings ) ) {
2240 $d = isset( $desc[$param] ) ? $desc[$param] :
'';
2241 if ( is_array( $d ) ) {
2243 $d = array_map(
function (
$line ) {
2244 if ( preg_match(
'/^\s+(\S+)\s+-\s+(.+)$/',
$line, $m ) ) {
2245 $line =
"\n;{$m[1]}:{$m[2]}";
2249 $d = implode(
' ', $d );
2252 if ( isset( $settings[self::PARAM_HELP_MSG] ) ) {
2255 $msg = $this->
msg(
"apihelp-{$path}-param-{$param}" );
2256 if ( !$msg->exists() ) {
2257 $msg = $this->
msg(
'api-help-fallback-parameter', $d );
2261 [ $prefix, $param, $name, $path ] );
2264 'Value in ApiBase::PARAM_HELP_MSG is not valid' );
2266 $msgs[$param] = [ $msg ];
2268 if ( isset( $settings[self::PARAM_TYPE] ) &&
2269 $settings[self::PARAM_TYPE] ===
'submodule'
2271 if ( isset( $settings[self::PARAM_SUBMODULE_MAP] ) ) {
2276 foreach ( $this->
getModuleManager()->getNames( $param ) as $submoduleName ) {
2277 $map[$submoduleName] = $prefix . $submoduleName;
2282 $deprecatedSubmodules = [];
2283 foreach ( $map as $v => $m ) {
2284 $arr = &$submodules;
2285 $isDeprecated =
false;
2290 $summary = $submod->getFinalSummary();
2291 $isDeprecated = $submod->isDeprecated();
2292 if ( $isDeprecated ) {
2293 $arr = &$deprecatedSubmodules;
2300 $key = $summary->getKey();
2301 $params = $summary->getParams();
2303 $key =
'api-help-undocumented-module';
2307 $arr[] = $m->setContext( $this->
getContext() );
2309 $msgs[$param] = array_merge( $msgs[$param], $submodules, $deprecatedSubmodules );
2310 } elseif ( isset( $settings[self::PARAM_HELP_MSG_PER_VALUE] ) ) {
2311 if ( !is_array( $settings[self::PARAM_HELP_MSG_PER_VALUE] ) ) {
2313 'ApiBase::PARAM_HELP_MSG_PER_VALUE is not valid' );
2315 if ( !is_array( $settings[self::PARAM_TYPE] ) ) {
2317 'ApiBase::PARAM_HELP_MSG_PER_VALUE may only be used when ' .
2318 'ApiBase::PARAM_TYPE is an array' );
2322 $deprecatedValues = isset( $settings[self::PARAM_DEPRECATED_VALUES] )
2326 foreach ( $settings[self::PARAM_TYPE] as
$value ) {
2327 if ( isset( $valueMsgs[
$value] ) ) {
2328 $msg = $valueMsgs[
$value];
2330 $msg =
"apihelp-{$path}-paramvalue-{$param}-{$value}";
2333 [ $prefix, $param, $name, $path,
$value ] );
2337 [ $m->getKey(),
'api-help-param-no-description' ],
2339 isset( $deprecatedValues[
$value] )
2341 $msgs[$param][] = $m->setContext( $this->
getContext() );
2344 "Value in ApiBase::PARAM_HELP_MSG_PER_VALUE for $value is not valid" );
2349 if ( isset( $settings[self::PARAM_HELP_MSG_APPEND] ) ) {
2350 if ( !is_array( $settings[self::PARAM_HELP_MSG_APPEND] ) ) {
2352 'Value for ApiBase::PARAM_HELP_MSG_APPEND is not an array' );
2354 foreach ( $settings[self::PARAM_HELP_MSG_APPEND] as $m ) {
2356 [ $prefix, $param, $name, $path ] );
2358 $msgs[$param][] = $m;
2361 'Value in ApiBase::PARAM_HELP_MSG_APPEND is not valid' );
2367 Hooks::run(
'APIGetParamDescriptionMessages', [ $this, &$msgs ] );
2394 $flags[] =
'writerights';
2397 $flags[] =
'mustbeposted';
2417 if ( $this->mModuleSource !==
false ) {
2422 $rClass =
new ReflectionClass( $this );
2423 $path = $rClass->getFileName();
2426 $this->mModuleSource =
null;
2429 $path = realpath( $path ) ?:
$path;
2432 if ( self::$extensionInfo ===
null ) {
2433 $extDir = $this->
getConfig()->get(
'ExtensionDirectory' );
2434 self::$extensionInfo = [
2435 realpath( __DIR__ ) ?: __DIR__ => [
2437 'name' =>
'MediaWiki',
2438 'license-name' =>
'GPL-2.0+',
2440 realpath(
"$IP/extensions" ) ?:
"$IP/extensions" =>
null,
2441 realpath( $extDir ) ?: $extDir =>
null,
2447 'license-name' =>
null,
2449 foreach ( $this->
getConfig()->
get(
'ExtensionCredits' ) as $group ) {
2450 foreach ( $group as
$ext ) {
2451 if ( !isset(
$ext[
'path'] ) || !isset(
$ext[
'name'] ) ) {
2456 $extpath =
$ext[
'path'];
2457 if ( !is_dir( $extpath ) ) {
2458 $extpath = dirname( $extpath );
2460 self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2461 array_intersect_key(
$ext, $keep );
2465 $extpath =
$ext[
'path'];
2466 if ( !is_dir( $extpath ) ) {
2467 $extpath = dirname( $extpath );
2469 self::$extensionInfo[realpath( $extpath ) ?: $extpath] =
2470 array_intersect_key(
$ext, $keep );
2477 if ( array_key_exists( $path, self::$extensionInfo ) ) {
2479 $this->mModuleSource = self::$extensionInfo[
$path];
2484 $path = dirname( $path );
2485 }
while ( $path !== $oldpath );
2488 $this->mModuleSource =
null;
2660 public function dieUsage( $description, $errorCode, $httpRespCode = 0, $extradata =
null ) {
2683 throw new MWException(
'Successful status passed to ApiBase::dieStatus' );
2686 $errors =
$status->getErrorsByType(
'error' );
2689 $errors =
$status->getErrorsByType(
'warning' );
2693 $errors = [ [
'message' =>
'unknownerror-nocode',
'params' => [] ] ];
2697 $msg = $errors[0][
'message'];
2699 $msg =
new Message( $errors[0][
'message'], $errors[0][
'params'] );
2702 $key = $msg->getKey();
2704 array_unshift(
$params, isset( self::$messageMap[$key] ) ? self::$messageMap[$key] : $key );
2723 'unknownerror' =>
'apierror-unknownerror',
2724 'unknownerror-nocode' =>
'apierror-unknownerror-nocode',
2725 'ns-specialprotected' =>
'ns-specialprotected',
2726 'protectedinterface' =>
'protectedinterface',
2727 'namespaceprotected' =>
'namespaceprotected',
2728 'customcssprotected' =>
'customcssprotected',
2729 'customjsprotected' =>
'customjsprotected',
2730 'cascadeprotected' =>
'cascadeprotected',
2731 'protectedpagetext' =>
'protectedpagetext',
2732 'protect-cantedit' =>
'protect-cantedit',
2733 'deleteprotected' =>
'deleteprotected',
2734 'badaccess-group0' =>
'badaccess-group0',
2735 'badaccess-groups' =>
'badaccess-groups',
2736 'titleprotected' =>
'titleprotected',
2737 'nocreate-loggedin' =>
'nocreate-loggedin',
2738 'nocreatetext' =>
'nocreatetext',
2739 'movenologintext' =>
'movenologintext',
2740 'movenotallowed' =>
'movenotallowed',
2741 'confirmedittext' =>
'confirmedittext',
2742 'blockedtext' =>
'apierror-blocked',
2743 'autoblockedtext' =>
'apierror-autoblocked',
2744 'systemblockedtext' =>
'apierror-systemblocked',
2745 'actionthrottledtext' =>
'apierror-ratelimited',
2746 'alreadyrolled' =>
'alreadyrolled',
2747 'cantrollback' =>
'cantrollback',
2748 'readonlytext' =>
'readonlytext',
2749 'sessionfailure' =>
'sessionfailure',
2750 'cannotdelete' =>
'cannotdelete',
2751 'notanarticle' =>
'apierror-missingtitle',
2752 'selfmove' =>
'selfmove',
2753 'immobile_namespace' =>
'apierror-immobilenamespace',
2754 'articleexists' =>
'articleexists',
2755 'hookaborted' =>
'hookaborted',
2756 'cantmove-titleprotected' =>
'cantmove-titleprotected',
2757 'imagenocrossnamespace' =>
'imagenocrossnamespace',
2758 'imagetypemismatch' =>
'imagetypemismatch',
2759 'ip_range_invalid' =>
'ip_range_invalid',
2760 'range_block_disabled' =>
'range_block_disabled',
2761 'nosuchusershort' =>
'nosuchusershort',
2762 'badipaddress' =>
'badipaddress',
2763 'ipb_expiry_invalid' =>
'ipb_expiry_invalid',
2764 'ipb_already_blocked' =>
'ipb_already_blocked',
2765 'ipb_blocked_as_range' =>
'ipb_blocked_as_range',
2766 'ipb_cant_unblock' =>
'ipb_cant_unblock',
2767 'mailnologin' =>
'apierror-cantsend',
2768 'ipbblocked' =>
'ipbblocked',
2769 'ipbnounblockself' =>
'ipbnounblockself',
2770 'usermaildisabled' =>
'usermaildisabled',
2771 'blockedemailuser' =>
'apierror-blockedfrommail',
2772 'notarget' =>
'apierror-notarget',
2773 'noemail' =>
'noemail',
2774 'rcpatroldisabled' =>
'rcpatroldisabled',
2775 'markedaspatrollederror-noautopatrol' =>
'markedaspatrollederror-noautopatrol',
2776 'delete-toobig' =>
'delete-toobig',
2777 'movenotallowedfile' =>
'movenotallowedfile',
2778 'userrights-no-interwiki' =>
'userrights-no-interwiki',
2779 'userrights-nodatabase' =>
'userrights-nodatabase',
2780 'nouserspecified' =>
'nouserspecified',
2781 'noname' =>
'noname',
2782 'summaryrequired' =>
'apierror-summaryrequired',
2783 'import-rootpage-invalid' =>
'import-rootpage-invalid',
2784 'import-rootpage-nosubpage' =>
'import-rootpage-nosubpage',
2785 'readrequired' =>
'apierror-readapidenied',
2786 'writedisabled' =>
'apierror-noapiwrite',
2787 'writerequired' =>
'apierror-writeapidenied',
2788 'missingparam' =>
'apierror-missingparam',
2789 'invalidtitle' =>
'apierror-invalidtitle',
2790 'nosuchpageid' =>
'apierror-nosuchpageid',
2791 'nosuchrevid' =>
'apierror-nosuchrevid',
2792 'nosuchuser' =>
'nosuchusershort',
2793 'invaliduser' =>
'apierror-invaliduser',
2794 'invalidexpiry' =>
'apierror-invalidexpiry',
2795 'pastexpiry' =>
'apierror-pastexpiry',
2796 'create-titleexists' =>
'apierror-create-titleexists',
2797 'missingtitle-createonly' =>
'apierror-missingtitle-createonly',
2798 'cantblock' =>
'apierror-cantblock',
2799 'canthide' =>
'apierror-canthide',
2800 'cantblock-email' =>
'apierror-cantblock-email',
2801 'cantunblock' =>
'apierror-permissiondenied-generic',
2802 'cannotundelete' =>
'cannotundelete',
2803 'permdenied-undelete' =>
'apierror-permissiondenied-generic',
2804 'createonly-exists' =>
'apierror-articleexists',
2805 'nocreate-missing' =>
'apierror-missingtitle',
2806 'cantchangecontentmodel' =>
'apierror-cantchangecontentmodel',
2807 'nosuchrcid' =>
'apierror-nosuchrcid',
2808 'nosuchlogid' =>
'apierror-nosuchlogid',
2809 'protect-invalidaction' =>
'apierror-protect-invalidaction',
2810 'protect-invalidlevel' =>
'apierror-protect-invalidlevel',
2811 'toofewexpiries' =>
'apierror-toofewexpiries',
2812 'cantimport' =>
'apierror-cantimport',
2813 'cantimport-upload' =>
'apierror-cantimport-upload',
2814 'importnofile' =>
'importnofile',
2815 'importuploaderrorsize' =>
'importuploaderrorsize',
2816 'importuploaderrorpartial' =>
'importuploaderrorpartial',
2817 'importuploaderrortemp' =>
'importuploaderrortemp',
2818 'importcantopen' =>
'importcantopen',
2819 'import-noarticle' =>
'import-noarticle',
2820 'importbadinterwiki' =>
'importbadinterwiki',
2821 'import-unknownerror' =>
'apierror-import-unknownerror',
2822 'cantoverwrite-sharedfile' =>
'apierror-cantoverwrite-sharedfile',
2823 'sharedfile-exists' =>
'apierror-fileexists-sharedrepo-perm',
2824 'mustbeposted' =>
'apierror-mustbeposted',
2825 'show' =>
'apierror-show',
2826 'specialpage-cantexecute' =>
'apierror-specialpage-cantexecute',
2827 'invalidoldimage' =>
'apierror-invalidoldimage',
2828 'nodeleteablefile' =>
'apierror-nodeleteablefile',
2829 'fileexists-forbidden' =>
'fileexists-forbidden',
2830 'fileexists-shared-forbidden' =>
'fileexists-shared-forbidden',
2831 'filerevert-badversion' =>
'filerevert-badversion',
2832 'noimageredirect-anon' =>
'apierror-noimageredirect-anon',
2833 'noimageredirect-logged' =>
'apierror-noimageredirect',
2834 'spamdetected' =>
'apierror-spamdetected',
2835 'contenttoobig' =>
'apierror-contenttoobig',
2836 'noedit-anon' =>
'apierror-noedit-anon',
2837 'noedit' =>
'apierror-noedit',
2838 'wasdeleted' =>
'apierror-pagedeleted',
2839 'blankpage' =>
'apierror-emptypage',
2840 'editconflict' =>
'editconflict',
2841 'hashcheckfailed' =>
'apierror-badmd5',
2842 'missingtext' =>
'apierror-notext',
2843 'emptynewsection' =>
'apierror-emptynewsection',
2844 'revwrongpage' =>
'apierror-revwrongpage',
2845 'undo-failure' =>
'undo-failure',
2846 'content-not-allowed-here' =>
'content-not-allowed-here',
2847 'edit-hook-aborted' =>
'edit-hook-aborted',
2848 'edit-gone-missing' =>
'edit-gone-missing',
2849 'edit-conflict' =>
'edit-conflict',
2850 'edit-already-exists' =>
'edit-already-exists',
2851 'invalid-file-key' =>
'apierror-invalid-file-key',
2852 'nouploadmodule' =>
'apierror-nouploadmodule',
2853 'uploaddisabled' =>
'uploaddisabled',
2854 'copyuploaddisabled' =>
'copyuploaddisabled',
2855 'copyuploadbaddomain' =>
'apierror-copyuploadbaddomain',
2856 'copyuploadbadurl' =>
'apierror-copyuploadbadurl',
2857 'filename-tooshort' =>
'filename-tooshort',
2858 'filename-toolong' =>
'filename-toolong',
2859 'illegal-filename' =>
'illegal-filename',
2860 'filetype-missing' =>
'filetype-missing',
2861 'mustbeloggedin' =>
'apierror-mustbeloggedin',
2870 $msg = Message::newFromSpecifier( $error );
2872 $key = $msg->getKey();
2873 if ( isset( self::$messageMap[$key] ) ) {
2875 array_unshift(
$params, self::$messageMap[$key] );
2896 if ( is_array( $error ) ) {
2897 $first = reset( $error );
2898 if ( is_array( $first ) ) {
2906 'code' => $msg->getApiCode(),
2908 $msg->inLanguage(
'en' )->useDatabase(
false )->text()
2910 'data' => $msg->getApiData()
2948 "apihelp-{$this->getModulePath()}-description",
2949 "apihelp-{$this->getModulePath()}-summary",
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfReadOnlyReason()
Check if the site is in read-only mode and return the message if so.
wfGetAllCallers( $limit=3)
Return a string consisting of callers in the stack.
wfTransactionalTimeLimit()
Set PHP's time limit to the larger of php.ini or $wgTransactionalTimeLimit.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking,...
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
This abstract class implements many basic API functions, and is the base of all API classes.
getModulePrefix()
Get parameter prefix (usually two letters or an empty string).
const PARAM_REQUIRED
(boolean) Is the parameter required?
const PARAM_MAX2
(integer) Max value allowed for the parameter for users with the apihighlimits right,...
const PARAM_SUBMODULE_MAP
(string[]) When PARAM_TYPE is 'submodule', map parameter values to submodule paths.
const PARAM_DEPRECATED
(boolean) Is the parameter deprecated (will show a warning)?
checkUserRightsAny( $rights, $user=null)
Helper function for permission-denied errors.
getParameter( $paramName, $parseLimit=true)
Get a value for the given parameter.
getModuleFromPath( $path)
Get a module from its module path.
getDB()
Gets a default replica DB connection object.
encodeParamName( $paramName)
This method mangles parameter name based on the prefix supplied to the constructor.
parameterNotEmpty( $x)
Callback function used in requireOnlyOneParameter to check whether required parameters are set.
static makeMessage( $msg, IContextSource $context, array $params=null)
Create a Message from a string or array.
const PARAM_MAX
(integer) Max value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
getWatchlistUser( $params)
Gets the user for whom to get the watchlist.
getParamDescription()
Returns an array of parameter descriptions.
isDeprecated()
Indicates whether this module is deprecated.
parseMsgInternal( $error)
dieContinueUsageIf( $condition)
Die with the 'badcontinue' error.
dieWithErrorOrDebug( $msg, $code=null, $data=null, $httpCode=null)
Will only set a warning instead of failing if the global $wgDebugAPI is set to true.
const PARAM_DEPRECATED_VALUES
(array) When PARAM_TYPE is an array, this indicates which of the values are deprecated.
array null bool $mModuleSource
getParent()
Get the parent of this module.
validateUser( $value, $encParamName)
Validate and normalize of parameters of type 'user'.
static dieDebug( $method, $message)
Internal code errors should be reported with this method.
getHelpUrls()
Return links to more detailed help pages about the module.
const PARAM_ISMULTI_LIMIT1
(integer) Maximum number of values, for normal users.
getErrorFromStatus( $status, &$extraData=null)
Get error (as code, string) from a Status object.
getModuleManager()
Get the module manager, or null if this module has no sub-modules.
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.
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
getCustomPrinter()
If the module may only be used with a certain format module, it should override this method to return...
setWatch( $watch, $titleObj, $userOption=null)
Set a watch (or unwatch) based the based on a watchlist parameter.
const PARAM_SENSITIVE
(boolean) Is the parameter sensitive? Note 'password'-type fields are always sensitive regardless of ...
parseMsg( $error)
Return the error message related to a certain array.
const PARAM_HELP_MSG_INFO
(array) Specify additional information tags for the parameter.
getErrorFormatter()
Get the error formatter.
isWriteMode()
Indicates whether this module requires write mode.
const PARAM_DFLT
(null|boolean|integer|string) Default value of the parameter.
isInternal()
Indicates whether this module is "internal" Internal API modules are not (yet) intended for 3rd party...
getFinalSummary()
Get final module summary.
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...
getDescription()
Returns the description string for this module.
const PARAM_HELP_MSG_APPEND
((string|array|Message)[]) Specify additional i18n messages to append to the normal message for this ...
dieReadOnly()
Helper function for readonly errors.
const PARAM_ALLOW_DUPLICATES
(boolean) Allow the same value to be set more than once when PARAM_ISMULTI is true?
getSummaryMessage()
Return the summary message.
modifyHelp(array &$help, array $options, array &$tocData)
Called from ApiHelp before the pieces are joined together and returned.
errorArrayToStatus(array $errors, User $user=null)
Turn an array of message keys or key+param arrays into a Status.
const PARAM_VALUE_LINKS
(string[]) When PARAM_TYPE is an array, this may be an array mapping those values to page titles whic...
__construct(ApiMain $mainModule, $moduleName, $modulePrefix='')
setContinuationManager( $manager)
Set the continuation manager.
addError( $msg, $code=null, $data=null)
Add an error for this module without aborting.
getExamplesMessages()
Returns usage examples for this module.
extractRequestParams( $parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user,...
addMessagesFromStatus(StatusValue $status, $types=[ 'warning', 'error'])
Add warnings and/or errors from a Status.
const PARAM_ISMULTI_LIMIT2
(integer) Maximum number of values, for users with the apihighimits right.
const PARAM_HELP_MSG_PER_VALUE
((string|array|Message)[]) When PARAM_TYPE is an array, this is an array mapping those values to $msg...
addDeprecation( $msg, $feature, $data=[])
Add a deprecation warning for this module.
dieUsageMsg( $error)
Output the error message related to a certain array.
getExtendedDescription()
Return the extended help text message.
getAllowedParams()
Returns an array of allowed parameters (parameter name) => (default value) or (parameter name) => (ar...
getModuleSourceInfo()
Returns information about the source of this module, if known.
const PARAM_SUBMODULE_PARAM_PREFIX
(string) When PARAM_TYPE is 'submodule', used to indicate the 'g' prefix added by ApiQueryGeneratorBa...
static escapeWikiText( $v)
A subset of wfEscapeWikiText for BC texts.
const PARAM_MIN
(integer) Lowest value allowed for the parameter, for PARAM_TYPE 'integer' and 'limit'.
mustBePosted()
Indicates whether this module must be called with a POST request.
getWebUITokenSalt(array $params)
Fetch the salt used in the Web UI corresponding to this module.
static array $extensionInfo
Maps extension paths to info arrays.
const LIMIT_BIG1
Fast query, standard limit.
isMain()
Returns true if this module is the main module ($this === $this->mMainModule), false otherwise.
const LIMIT_SML2
Slow query, apihighlimits limit.
handleParamNormalization( $paramName, $value, $rawValue)
Handle when a parameter was Unicode-normalized.
validateLimit( $paramName, &$value, $min, $max, $botMax=null, $enforceLimits=false)
Validate the value against the minimum and user/bot maximum limits.
getFinalDescription()
Get final module description, after hooks have had a chance to tweak it as needed.
warnOrDie(ApiMessage $msg, $enforceLimits=false)
Adds a warning to the output, else dies.
static truncateArray(&$arr, $limit)
Truncate an array to a certain length.
getResult()
Get the result object.
requireMaxOneParameter( $params, $required)
Die if more than one of a certain set of parameters is set and not false.
needsToken()
Returns the token type this module requires in order to execute.
getDescriptionMessage()
Return the description message.
getParameterFromSettings( $paramName, $paramSettings, $parseLimit)
Using the settings determine the value for the given parameter.
getModulePath()
Get the path to this module.
const PARAM_RANGE_ENFORCE
(boolean) For PARAM_TYPE 'integer', enforce PARAM_MIN and PARAM_MAX?
logFeatureUsage( $feature)
Write logging information for API features to a debug log, for usage analysis.
const PARAM_EXTRA_NAMESPACES
(int[]) When PARAM_TYPE is 'namespace', include these as additional possible values.
shouldCheckMaxlag()
Indicates if this module needs maxlag to be checked.
getHelpFlags()
Generates the list of flags for the help screen and for action=paraminfo.
const LIMIT_SML1
Slow query, standard limit.
dieUsageMsgOrDebug( $error)
Will only set a warning instead of failing if the global $wgDebugAPI is set to true.
getFinalParams( $flags=0)
Get final list of parameters, after hooks have had a chance to tweak it as needed.
getWatchlistValue( $watchlist, $titleObj, $userOption=null)
Return true if we're to watch the page, false if not, null if no change.
isReadMode()
Indicates whether this module requires read rights.
getExamples()
Returns usage examples for this module.
dieWithException( $exception, array $options=[])
Abort execution with an error derived from an exception.
const PARAM_HELP_MSG
(string|array|Message) Specify an alternative i18n documentation message for this parameter.
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
requireAtLeastOneParameter( $params, $required)
Die if none of a certain set of parameters is set and not false.
getTitleFromTitleOrPageId( $params)
Get a Title object from a title or pageid param, if possible.
const PARAM_ALL
(boolean|string) When PARAM_TYPE has a defined set of values and PARAM_ISMULTI is true,...
const GET_VALUES_FOR_HELP
getAllowedParams() flag: When set, the result could take longer to generate, but should be more thoro...
const LIMIT_BIG2
Fast query, apihighlimits limit.
getModuleName()
Get the name of the module being executed by this instance.
getTitleOrPageId( $params, $load=false)
Get a WikiPage object from a title or pageid param, if possible.
validateTimestamp( $value, $encParamName)
Validate and normalize of parameters of type 'timestamp'.
dieStatus(StatusValue $status)
Throw an ApiUsageException based on the Status object.
useTransactionalTimeLimit()
Call wfTransactionalTimeLimit() if this request was POSTed.
getFinalParamDescription()
Get final parameter descriptions, after hooks have had a chance to tweak it as needed.
checkTitleUserPermissions(Title $title, $actions, $user=null)
Helper function for permission-denied errors.
dieBlocked(Block $block)
Throw an ApiUsageException, which will (if uncaught) call the main module's error handler and die wit...
dynamicParameterDocumentation()
Indicate if the module supports dynamically-determined parameters that cannot be included in self::ge...
getModuleProfileName( $db=false)
getContinuationManager()
Get the continuation manager.
explodeMultiValue( $value, $limit)
Split a multi-valued parameter string, like explode()
execute()
Evaluates the parameters, performs the requested query, and sets up the result.
dieUsage( $description, $errorCode, $httpRespCode=0, $extradata=null)
Throw an ApiUsageException, which will (if uncaught) call the main module's error handler and die wit...
validateToken( $token, array $params)
Validate the supplied token.
getConditionalRequestData( $condition)
Returns data for HTTP conditional request mechanisms.
requireOnlyOneParameter( $params, $required)
Die if none or more than one of a certain set of parameters is set and not false.
const PARAM_ISMULTI
(boolean) Accept multiple pipe-separated values for this parameter (e.g.
lacksSameOriginSecurity()
Returns true if the current request breaks the same-origin policy.
Message subclass that prepends wikitext for API help.
This is the main API class, used for both external and internal processing.
Extension of Message implementing IApiMessage.
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
static getTokenTypeSalts()
Get the salts for known token types.
static getToken(User $user, MediaWiki\Session\Session $session, $salt)
Get a token from a salt.
static getBlockInfo(Block $block)
Get basic info about a given block.
Extension of RawMessage implementing IApiMessage.
Exception used to abort API execution with an error.
static newWithMessage(ApiBase $module=null, $msg, $code=null, $data=null, $httpCode=0)
getType()
Get the type of target for this particular block.
The simplest way of implementing IContextSource is to hold a RequestContext as a member variable and ...
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
getUser()
Get the User object.
getRequest()
Get the WebRequest object.
getConfig()
Get the Config object.
getContext()
Get the base IContextSource object.
setContext(IContextSource $context)
Set the IContextSource object.
The Message class provides methods which fulfil two basic services:
Variant of the Message class.
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Represents a title within MediaWiki.
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
static doWatchOrUnwatch( $watch, Title $title, User $user)
Watch or unwatch a page.
static newFromID( $id, $from='fromdb')
Constructor from a page id.
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
the array() calling protocol came about after MediaWiki 1.4rc1.
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
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
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
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
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 "<div ...>$1</div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
it s the revision text itself In either if gzip is the revision text is gzipped $flags
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
Allows to change the fields on the form that will be generated $name
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). '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
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 local account $user
Interface for messages with machine-readable data for use by the API.
Interface for objects which can provide a MediaWiki context on request.