Go to the documentation of this file.
28 use Wikimedia\Timestamp\TimestampException;
60 'login' =>
'ApiLogin',
61 'clientlogin' =>
'ApiClientLogin',
62 'logout' =>
'ApiLogout',
63 'createaccount' =>
'ApiAMCreateAccount',
64 'linkaccount' =>
'ApiLinkAccount',
65 'unlinkaccount' =>
'ApiRemoveAuthenticationData',
66 'changeauthenticationdata' =>
'ApiChangeAuthenticationData',
67 'removeauthenticationdata' =>
'ApiRemoveAuthenticationData',
68 'resetpassword' =>
'ApiResetPassword',
69 'query' =>
'ApiQuery',
70 'expandtemplates' =>
'ApiExpandTemplates',
71 'parse' =>
'ApiParse',
72 'stashedit' =>
'ApiStashEdit',
73 'opensearch' =>
'ApiOpenSearch',
74 'feedcontributions' =>
'ApiFeedContributions',
75 'feedrecentchanges' =>
'ApiFeedRecentChanges',
76 'feedwatchlist' =>
'ApiFeedWatchlist',
78 'paraminfo' =>
'ApiParamInfo',
80 'compare' =>
'ApiComparePages',
81 'tokens' =>
'ApiTokens',
82 'checktoken' =>
'ApiCheckToken',
83 'cspreport' =>
'ApiCSPReport',
84 'validatepassword' =>
'ApiValidatePassword',
87 'purge' =>
'ApiPurge',
88 'setnotificationtimestamp' =>
'ApiSetNotificationTimestamp',
89 'rollback' =>
'ApiRollback',
90 'delete' =>
'ApiDelete',
91 'undelete' =>
'ApiUndelete',
92 'protect' =>
'ApiProtect',
93 'block' =>
'ApiBlock',
94 'unblock' =>
'ApiUnblock',
96 'edit' =>
'ApiEditPage',
97 'upload' =>
'ApiUpload',
98 'filerevert' =>
'ApiFileRevert',
99 'emailuser' =>
'ApiEmailUser',
100 'watch' =>
'ApiWatch',
101 'patrol' =>
'ApiPatrol',
102 'import' =>
'ApiImport',
103 'clearhasmsg' =>
'ApiClearHasMsg',
104 'userrights' =>
'ApiUserrights',
105 'options' =>
'ApiOptions',
106 'imagerotate' =>
'ApiImageRotate',
107 'revisiondelete' =>
'ApiRevisionDelete',
108 'managetags' =>
'ApiManageTags',
110 'mergehistory' =>
'ApiMergeHistory',
111 'setpagelanguage' =>
'ApiSetPageLanguage',
118 'json' =>
'ApiFormatJson',
119 'jsonfm' =>
'ApiFormatJson',
120 'php' =>
'ApiFormatPhp',
121 'phpfm' =>
'ApiFormatPhp',
122 'xml' =>
'ApiFormatXml',
123 'xmlfm' =>
'ApiFormatXml',
124 'rawfm' =>
'ApiFormatJson',
125 'none' =>
'ApiFormatNone',
137 'msg' =>
'right-writeapi',
141 'msg' =>
'api-help-right-apihighlimits',
196 parent::__construct( $this, $this->mInternalMode ?
'main_int' :
'main' );
200 if ( !$this->mInternalMode ) {
203 $originHeader =
$request->getHeader(
'Origin' );
204 if ( $originHeader ===
false ) {
207 $originHeader = trim( $originHeader );
208 $origins = preg_split(
'/\s+/', $originHeader );
210 $sessionCookies = array_intersect(
211 array_keys( $_COOKIE ),
212 MediaWiki\Session\SessionManager::singleton()->getVaryCookies()
214 if ( $origins && $sessionCookies && (
215 count( $origins ) !== 1 || !self::matchOrigin(
217 $config->get(
'CrossSiteAJAXdomains' ),
218 $config->get(
'CrossSiteAJAXdomainExceptions' )
221 LoggerFactory::getInstance(
'cors' )->warning(
222 'Non-whitelisted CORS request with session cookies', [
223 'origin' => $originHeader,
224 'cookies' => $sessionCookies,
236 wfDebug(
"API: stripping user credentials when the same-origin policy is not applied\n" );
237 $wgUser =
new User();
239 $request->response()->header(
'MediaWiki-Login-Suppressed: true' );
247 $uselang =
$request->getVal(
'uselang', self::API_DEFAULT_USELANG );
248 if ( $uselang ===
'user' ) {
252 if ( $uselang ===
'content' ) {
258 if ( !$this->mInternalMode ) {
267 $errorFormat =
$request->getVal(
'errorformat',
'bc' );
268 $errorLangCode =
$request->getVal(
'errorlang',
'uselang' );
269 $errorsUseDB =
$request->getCheck(
'errorsuselocal' );
270 if ( in_array( $errorFormat, [
'plaintext',
'wikitext',
'html',
'raw',
'none' ],
true ) ) {
271 if ( $errorLangCode ===
'uselang' ) {
273 } elseif ( $errorLangCode ===
'content' ) {
281 $this->mResult, $errorLang, $errorFormat, $errorsUseDB
289 $this->mModuleMgr->addModules( self::$Modules,
'action' );
290 $this->mModuleMgr->addModules( $config->get(
'APIModules' ),
'action' );
291 $this->mModuleMgr->addModules( self::$Formats,
'format' );
292 $this->mModuleMgr->addModules( $config->get(
'APIFormatModules' ),
'format' );
294 Hooks::run(
'ApiMain::moduleManager', [ $this->mModuleMgr ] );
296 $this->mContinuationManager =
null;
297 $this->mEnableWrite = $enableWrite;
299 $this->mSquidMaxage = -1;
300 $this->mCommit =
false;
332 if (
$request->getVal(
'callback' ) !== null ) {
338 if (
$request->getVal(
'origin' ) ===
'*' ) {
345 if (
$request->getHeader(
'Treat-as-Untrusted' ) !==
false ) {
376 if ( $manager !==
null ) {
378 throw new InvalidArgumentException( __METHOD__ .
': Was passed ' .
379 is_object( $manager ) ? get_class( $manager ) : gettype( $manager )
382 if ( $this->mContinuationManager !==
null ) {
383 throw new UnexpectedValueException(
384 __METHOD__ .
': tried to set manager from ' . $manager->getSource() .
385 ' when a manager is already set from ' . $this->mContinuationManager->getSource()
389 $this->mContinuationManager = $manager;
417 'max-age' => $maxage,
418 's-maxage' => $maxage
448 if ( !in_array( $mode, [
'private',
'public',
'anon-public-user-private' ] ) ) {
449 wfDebug( __METHOD__ .
": unrecognised cache mode \"$mode\"\n" );
457 if ( $mode !==
'private' ) {
458 wfDebug( __METHOD__ .
": ignoring request for $mode cache mode, private wiki\n" );
464 if ( $mode ===
'public' && $this->
getParameter(
'uselang' ) ===
'user' ) {
469 wfDebug( __METHOD__ .
": downgrading cache mode 'public' to " .
470 "'anon-public-user-private' due to uselang=user\n" );
471 $mode =
'anon-public-user-private';
474 wfDebug( __METHOD__ .
": setting cache mode $mode\n" );
475 $this->mCacheMode = $mode;
500 $printer = $this->mModuleMgr->getModule( $format,
'format' );
501 if ( $printer ===
null ) {
514 if ( $this->mInternalMode ) {
534 if ( $this->
getRequest()->getMethod() ===
'OPTIONS' ) {
540 $obLevel = ob_get_level();
543 $t = microtime(
true );
547 $runTime = microtime(
true ) -
$t;
549 if ( $this->mModule->isWriteMode() && $this->
getRequest()->wasPosted() ) {
550 MediaWikiServices::getInstance()->getStatsdDataFactory()->timing(
551 'api.' . $this->mModule->getModuleName() .
'.executeTiming', 1000 * $runTime
554 }
catch ( Exception
$e ) {
569 while ( ob_get_level() > $obLevel ) {
600 $headerStr =
'MediaWiki-API-Error: ' . join(
', ', $errCodes );
616 $this->
addWarning(
'apiwarn-errorprinterfailed' );
619 $this->mPrinter->addWarning( $error );
620 }
catch ( Exception $ex2 ) {
630 [
'apiwarn-errorprinterfailed-ex', $ex->getMessage() ],
'errorprinterfailed'
634 $this->mPrinter =
null;
636 $this->mPrinter->forceDefaultParams();
637 if (
$e->getCode() ) {
659 $main->handleException(
$e );
660 $main->logRequest( 0,
$e );
661 }
catch ( Exception $e2 ) {
667 $main->sendCacheHeaders(
true );
688 if ( $originParam ===
null ) {
696 $matchedOrigin =
false;
697 $allowTiming =
false;
700 if ( $originParam ===
'*' ) {
706 $matchedOrigin =
true;
708 $allowCredentials =
'false';
714 $originHeader =
$request->getHeader(
'Origin' );
715 if ( $originHeader ===
false ) {
718 $originHeader = trim( $originHeader );
719 $origins = preg_split(
'/\s+/', $originHeader );
722 if ( !in_array( $originParam, $origins ) ) {
726 $response->header(
'Cache-Control: no-cache' );
727 echo
"'origin' parameter does not match Origin header\n";
735 $config->get(
'CrossSiteAJAXdomains' ),
736 $config->get(
'CrossSiteAJAXdomainExceptions' )
739 $allowOrigin = $originHeader;
740 $allowCredentials =
'true';
741 $allowTiming = $originHeader;
744 if ( $matchedOrigin ) {
745 $requestedMethod =
$request->getHeader(
'Access-Control-Request-Method' );
746 $preflight =
$request->getMethod() ===
'OPTIONS' && $requestedMethod !==
false;
749 if ( $requestedMethod !==
'POST' && $requestedMethod !==
'GET' ) {
751 $response->header(
'MediaWiki-CORS-Rejection: Unsupported method requested in preflight' );
755 $requestedHeaders =
$request->getHeader(
'Access-Control-Request-Headers' );
756 if ( $requestedHeaders !==
false ) {
757 if ( !self::matchRequestedHeaders( $requestedHeaders ) ) {
758 $response->header(
'MediaWiki-CORS-Rejection: Unsupported header requested in preflight' );
761 $response->header(
'Access-Control-Allow-Headers: ' . $requestedHeaders );
765 $response->header(
'Access-Control-Allow-Methods: POST, GET' );
766 } elseif (
$request->getMethod() !==
'POST' &&
$request->getMethod() !==
'GET' ) {
769 'MediaWiki-CORS-Rejection: Unsupported method for simple request or actual request'
774 $response->header(
"Access-Control-Allow-Origin: $allowOrigin" );
775 $response->header(
"Access-Control-Allow-Credentials: $allowCredentials" );
777 if ( $allowTiming !==
false ) {
778 $response->header(
"Timing-Allow-Origin: $allowTiming" );
783 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag, '
784 .
'MediaWiki-Login-Suppressed'
788 $response->header(
'MediaWiki-CORS-Rejection: Origin mismatch' );
792 $this->
getOutput()->addVaryHeader(
'Origin' );
807 foreach ( $rules
as $rule ) {
808 if ( preg_match( self::wildcardToRegex( $rule ),
$value ) ) {
810 foreach ( $exceptions
as $exc ) {
811 if ( preg_match( self::wildcardToRegex( $exc ),
$value ) ) {
831 if ( trim( $requestedHeaders ) ===
'' ) {
834 $requestedHeaders = explode(
',', $requestedHeaders );
835 $allowedAuthorHeaders = array_flip( [
848 foreach ( $requestedHeaders
as $rHeader ) {
849 $rHeader = strtolower( trim( $rHeader ) );
850 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
851 wfDebugLog(
'api',
'CORS preflight failed on requested header: ' . $rHeader );
867 $wildcard = preg_quote( $wildcard,
'/' );
868 $wildcard = str_replace(
874 return "/^https?:\/\/$wildcard$/";
886 $out->addVaryHeader(
'Treat-as-Untrusted' );
890 if ( $config->get(
'VaryOnXFP' ) ) {
891 $out->addVaryHeader(
'X-Forwarded-Proto' );
894 if ( !$isError && $this->mModule &&
897 $etag = $this->mModule->getConditionalRequestData(
'etag' );
898 if ( $etag !==
null ) {
901 $lastMod = $this->mModule->getConditionalRequestData(
'last-modified' );
902 if ( $lastMod !==
null ) {
914 if ( isset( $this->mCacheControl[
'max-age'] ) ) {
915 $maxage = $this->mCacheControl[
'max-age'];
916 } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) ||
917 $this->mCacheMode !==
'private'
921 $privateCache =
'private, must-revalidate, max-age=' . $maxage;
923 if ( $this->mCacheMode ==
'private' ) {
924 $response->header(
"Cache-Control: $privateCache" );
928 $useKeyHeader = $config->get(
'UseKeyHeader' );
929 if ( $this->mCacheMode ==
'anon-public-user-private' ) {
930 $out->addVaryHeader(
'Cookie' );
932 if ( $useKeyHeader ) {
934 if (
$out->haveCacheVaryCookies() ) {
936 $response->header(
"Cache-Control: $privateCache" );
940 } elseif (
MediaWiki\Session\SessionManager::getGlobalSession()->isPersistent() ) {
943 $response->header(
"Cache-Control: $privateCache" );
951 if ( $useKeyHeader ) {
956 if ( !isset( $this->mCacheControl[
's-maxage'] ) ) {
957 $this->mCacheControl[
's-maxage'] = $this->
getParameter(
'smaxage' );
959 if ( !isset( $this->mCacheControl[
'max-age'] ) ) {
960 $this->mCacheControl[
'max-age'] = $this->
getParameter(
'maxage' );
963 if ( !$this->mCacheControl[
's-maxage'] && !$this->mCacheControl[
'max-age'] ) {
967 $response->header(
"Cache-Control: $privateCache" );
972 $this->mCacheControl[
'public'] =
true;
975 $maxAge = min( $this->mCacheControl[
's-maxage'], $this->mCacheControl[
'max-age'] );
976 $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
983 if ( is_bool(
$value ) ) {
985 $ccHeader .= $separator .
$name;
989 $ccHeader .= $separator .
"$name=$value";
994 $response->header(
"Cache-Control: $ccHeader" );
1001 if ( !isset( $this->mPrinter ) ) {
1002 $value = $this->
getRequest()->getVal(
'format', self::API_DEFAULT_FORMAT );
1003 if ( !$this->mModuleMgr->isDefined(
$value,
'format' ) ) {
1011 if ( !$this->mPrinter->canPrintErrors() ) {
1037 foreach (
$e->getStatusValue()->getErrorsByType(
$type )
as $error ) {
1040 } elseif (
$type !==
'error' ) {
1044 $data = MediaWiki\quietCall( [
$e,
'getMessageArray' ] );
1045 $code = $data[
'code'];
1046 $info = $data[
'info'];
1047 unset( $data[
'code'], $data[
'info'] );
1052 $class = preg_replace(
'#^Wikimedia\\\Rdbms\\\#',
'', get_class(
$e ) );
1053 $code =
'internal_api_error_' . $class;
1054 if ( (
$e instanceof
DBQueryError ) && !$config->get(
'ShowSQLErrors' ) ) {
1058 'apierror-exceptioncaught',
1061 ?
$e->getMessageObject()
1082 $errors =
$result->getResultData( [
'errors' ] );
1083 $warnings =
$result->getResultData( [
'warnings' ] );
1085 if ( $warnings !==
null ) {
1088 if ( $errors !==
null ) {
1092 foreach ( $errors
as $error ) {
1093 if ( isset( $error[
'code'] ) ) {
1094 $errorCodes[$error[
'code']] =
true;
1102 $errorCodes[$msg->getApiCode()] =
true;
1103 $formatter->addError( $modulePath, $msg );
1106 $formatter->addWarning( $modulePath, $msg );
1112 $path = [
'error' ];
1122 $this->
msg(
'api-usage-docref',
$link )->inLanguage( $formatter->getLanguage() )->
text()
1124 . $this->
msg(
'api-usage-mailinglist-ref' )->inLanguage( $formatter->getLanguage() )->
text()
1128 if ( $config->get(
'ShowExceptionDetails' ) &&
1129 ( !
$e instanceof
DBError || $config->get(
'ShowDBErrorBacktrace' ) )
1134 $this->
msg(
'api-exception-trace',
1139 )->inLanguage( $formatter->getLanguage() )->
text()
1147 return array_keys( $errorCodes );
1159 if ( $requestid !==
null ) {
1163 if ( $this->
getConfig()->
get(
'ShowHostnames' ) && (
1164 in_array(
'servedby', $force,
true ) || $this->
getParameter(
'servedby' )
1190 $this->mAction =
$params[
'action'];
1203 $module = $this->mModuleMgr->getModule( $this->mAction,
'action' );
1204 if ( $module ===
null ) {
1206 [
'apierror-unknownaction',
wfEscapeWikiText( $this->mAction ) ],
'unknown_action'
1209 $moduleParams = $module->extractRequestParams();
1212 if ( $module->needsToken() ===
true ) {
1214 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1215 'See documentation for ApiBase::needsToken for details.'
1218 if ( $module->needsToken() ) {
1219 if ( !$module->mustBePosted() ) {
1221 "Module '{$module->getModuleName()}' must require POST to use tokens."
1225 if ( !isset( $moduleParams[
'token'] ) ) {
1226 $module->dieWithError( [
'apierror-missingparam',
'token' ] );
1229 $module->requirePostedParameters( [
'token' ] );
1231 if ( !$module->validateToken( $moduleParams[
'token'], $moduleParams ) ) {
1232 $module->dieWithError(
'apierror-badtoken' );
1243 $dbLag = MediaWikiServices::getInstance()->getDBLoadBalancer()->getMaxLag();
1245 'host' => $dbLag[0],
1250 $jobQueueLagFactor = $this->
getConfig()->get(
'JobQueueIncludeInMaxLagFactor' );
1251 if ( $jobQueueLagFactor ) {
1254 $jobQueueLag = $totalJobs / (float)$jobQueueLagFactor;
1255 if ( $jobQueueLag > $lagInfo[
'lag'] ) {
1258 'lag' => $jobQueueLag,
1259 'type' =>
'jobqueue',
1260 'jobs' => $totalJobs,
1275 if ( $module->shouldCheckMaxlag() && isset(
$params[
'maxlag'] ) ) {
1278 if ( $lagInfo[
'lag'] > $maxLag ) {
1281 $response->header(
'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1282 $response->header(
'X-Database-Lag: ' . intval( $lagInfo[
'lag'] ) );
1284 if ( $this->
getConfig()->
get(
'ShowHostnames' ) ) {
1286 [
'apierror-maxlag', $lagInfo[
'lag'], $lagInfo[
'host'] ],
1292 $this->
dieWithError( [
'apierror-maxlag-generic', $lagInfo[
'lag'] ],
'maxlag', $lagInfo );
1321 if ( $this->mInternalMode ) {
1326 if ( $this->
getRequest()->getMethod() !==
'GET' && $this->
getRequest()->getMethod() !==
'HEAD' ) {
1333 $ifNoneMatch = array_diff(
1337 if ( $ifNoneMatch ) {
1338 if ( $ifNoneMatch === [
'*' ] ) {
1342 $etag = $module->getConditionalRequestData(
'etag' );
1345 if ( $ifNoneMatch && $etag !==
null ) {
1346 $test = substr( $etag, 0, 2 ) ===
'W/' ? substr( $etag, 2 ) : $etag;
1347 $match = array_map(
function (
$s ) {
1348 return substr(
$s, 0, 2 ) ===
'W/' ? substr(
$s, 2 ) :
$s;
1350 $return304 = in_array( $test, $match,
true );
1357 $i = strpos(
$value,
';' );
1358 if ( $i !==
false ) {
1367 $ts->getTimestamp( TS_RFC2822 ) ===
$value ||
1369 $ts->format(
'l, d-M-y H:i:s' ) .
' GMT' ===
$value ||
1371 $ts->format(
'D M j H:i:s Y' ) ===
$value ||
1372 $ts->format(
'D M j H:i:s Y' ) ===
$value
1374 $lastMod = $module->getConditionalRequestData(
'last-modified' );
1375 if ( $lastMod !==
null ) {
1379 'user' => $this->
getUser()->getTouched(),
1380 'epoch' => $this->
getConfig()->get(
'CacheEpoch' ),
1382 if ( $this->
getConfig()->
get(
'UseSquid' ) ) {
1385 TS_MW, time() - $this->
getConfig()->
get(
'SquidMaxage' )
1389 $lastMod = max( $modifiedTimes );
1390 $return304 =
wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW );
1393 }
catch ( TimestampException
$e ) {
1400 $this->
getRequest()->response()->statusHeader( 304 );
1403 MediaWiki\suppressWarnings();
1404 ini_set(
'zlib.output_compression', 0 );
1405 MediaWiki\restoreWarnings();
1421 !
$user->isAllowed(
'read' )
1426 if ( $module->isWriteMode() ) {
1427 if ( !$this->mEnableWrite ) {
1429 } elseif ( !
$user->isAllowed(
'writeapi' ) ) {
1431 } elseif ( $this->
getRequest()->getHeader(
'Promise-Non-Write-API-Action' ) ) {
1432 $this->
dieWithError(
'apierror-promised-nonwrite-api' );
1440 if ( !
Hooks::run(
'ApiCheckCanExecute', [ $module,
$user, &$message ] ) ) {
1454 if ( $module->isWriteMode()
1456 &&
wfGetLB()->getServerCount() > 1
1468 $lagLimit = $this->
getConfig()->get(
'APIMaxLagThreshold' );
1469 $laggedServers = [];
1471 foreach ( $loadBalancer->getLagTimes()
as $serverIndex => $lag ) {
1472 if ( $lag > $lagLimit ) {
1474 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) .
" ({$lag}s)";
1479 $replicaCount =
wfGetLB()->getServerCount() - 1;
1480 if ( $numLagged >= ceil( $replicaCount / 2 ) ) {
1481 $laggedServers = implode(
', ', $laggedServers );
1484 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1490 [
'readonlyreason' =>
"Waiting for $numLagged lagged database(s)" ]
1500 if ( isset(
$params[
'assert'] ) ) {
1502 switch (
$params[
'assert'] ) {
1504 if (
$user->isAnon() ) {
1509 if ( !
$user->isAllowed(
'bot' ) ) {
1515 if ( isset(
$params[
'assertuser'] ) ) {
1517 if ( !$assertUser || !$this->
getUser()->equals( $assertUser ) ) {
1532 if ( !
$request->wasPosted() && $module->mustBePosted() ) {
1539 $this->mPrinter = $module->getCustomPrinter();
1540 if ( is_null( $this->mPrinter ) ) {
1545 if (
$request->getProtocol() ===
'http' && (
1546 $request->getSession()->shouldForceHTTPS() ||
1547 ( $this->
getUser()->isLoggedIn() &&
1548 $this->
getUser()->requiresHTTPS() )
1550 $this->
addDeprecation(
'apiwarn-deprecation-httpsexpected',
'https-expected' );
1560 $this->mModule = $module;
1562 if ( !$this->mInternalMode ) {
1576 if ( !$this->mInternalMode ) {
1584 Hooks::run(
'APIAfterExecute', [ &$module ] );
1588 if ( !$this->mInternalMode ) {
1602 $limits = $this->
getConfig()->get(
'TrxProfilerLimits' );
1604 $trxProfiler->setLogger( LoggerFactory::getInstance(
'DBPerformance' ) );
1605 if ( $this->
getRequest()->hasSafeMethod() ) {
1606 $trxProfiler->setExpectations( $limits[
'GET'], __METHOD__ );
1608 $trxProfiler->setExpectations( $limits[
'POST-nonwrite'], __METHOD__ );
1611 $trxProfiler->setExpectations( $limits[
'POST'], __METHOD__ );
1627 'timeSpentBackend' => (int)round(
$time * 1000 ),
1628 'hadError' =>
$e !==
null,
1635 $logCtx[
'errorCodes'][] = $msg->getApiCode();
1640 $msg =
"API {$request->getMethod()} " .
1642 " {$logCtx['ip']} " .
1643 "T={$logCtx['timeSpentBackend']}ms";
1652 if ( isset( $sensitive[
$name] ) ) {
1654 $encValue =
'[redacted]';
1655 } elseif ( strlen(
$value ) > 256 ) {
1663 $msg .=
" {$name}={$encValue}";
1668 wfDebugLog(
'ApiAction',
'',
'private', $logCtx );
1679 $chars =
';@$!*(),/:';
1680 $numChars = strlen( $chars );
1681 for ( $i = 0; $i < $numChars; $i++ ) {
1682 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1686 return strtr( rawurlencode(
$s ), $table );
1694 return array_keys( $this->mParamsUsed );
1702 $this->mParamsUsed += array_fill_keys( (
array)
$params,
true );
1711 return array_keys( $this->mParamsSensitive );
1720 $this->mParamsSensitive += array_fill_keys( (
array)
$params,
true );
1730 $this->mParamsUsed[
$name] =
true;
1733 if (
$ret ===
null ) {
1762 $this->mParamsUsed[
$name] =
true;
1773 $allParams = $this->
getRequest()->getValueNames();
1775 if ( !$this->mInternalMode ) {
1777 $printerParams = $this->mPrinter->encodeParamName(
1778 array_keys( $this->mPrinter->getFinalParams() ?: [] )
1780 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1782 $unusedParams = array_diff( $allParams, $paramsUsed );
1785 if (
count( $unusedParams ) ) {
1787 'apierror-unrecognizedparams',
1788 Message::listParam( array_map(
'wfEscapeWikiText', $unusedParams ),
'comma' ),
1789 count( $unusedParams )
1800 if ( $this->
getConfig()->
get(
'DebugAPI' ) !==
false ) {
1807 $printer->setHttpStatus( $httpCode );
1809 $printer->execute();
1810 $printer->closePrinter();
1852 'requestid' =>
null,
1853 'servedby' =>
false,
1854 'curtimestamp' =>
false,
1855 'responselanginfo' =>
false,
1867 'errorsuselocal' => [
1877 =>
'apihelp-help-example-main',
1878 'action=help&recursivesubmodules=1'
1879 =>
'apihelp-help-example-recursive',
1888 foreach ( $oldHelp
as $k => $v ) {
1889 if ( $k ===
'submodules' ) {
1890 $help[
'permissions'] =
'';
1894 $help[
'datatypes'] =
'';
1895 $help[
'credits'] =
'';
1899 [
'class' =>
'apihelp-block apihelp-permissions' ] );
1900 $m = $this->
msg(
'api-help-permissions' );
1901 if ( !$m->isDisabled() ) {
1903 $m->numParams(
count( self::$mRights ) )->parse()
1907 foreach ( self::$mRights
as $right => $rightMsg ) {
1910 $rightMsg = $this->
msg( $rightMsg[
'msg'], $rightMsg[
'params'] )->parse();
1913 $groups = array_map(
function ( $group ) {
1914 return $group ==
'*' ?
'all' : $group;
1918 $this->
msg(
'api-help-permissions-granted-to' )
1919 ->numParams(
count( $groups ) )
1920 ->params( Message::listParam( $groups ) )
1928 if ( empty(
$options[
'nolead'] ) ) {
1930 $tocnumber = &
$options[
'tocnumber'];
1932 $header = $this->
msg(
'api-help-datatypes-header' )->parse();
1934 $id = Sanitizer::escapeIdForAttribute(
'main/datatypes', Sanitizer::ID_PRIMARY );
1935 $idFallback = Sanitizer::escapeIdForAttribute(
'main/datatypes', Sanitizer::ID_FALLBACK );
1937 ' class="apihelp-header"',
1944 if ( $id !==
'main/datatypes' && $idFallback !==
'main/datatypes' ) {
1945 $headline =
'<div id="main/datatypes"></div>' . $headline;
1947 $help[
'datatypes'] .= $headline;
1948 $help[
'datatypes'] .= $this->
msg(
'api-help-datatypes' )->parseAsBlock();
1949 if ( !isset( $tocData[
'main/datatypes'] ) ) {
1950 $tocnumber[$level]++;
1951 $tocData[
'main/datatypes'] = [
1952 'toclevel' =>
count( $tocnumber ),
1954 'anchor' =>
'main/datatypes',
1956 'number' => implode(
'.', $tocnumber ),
1961 $header = $this->
msg(
'api-credits-header' )->parse();
1962 $id = Sanitizer::escapeIdForAttribute(
'main/credits', Sanitizer::ID_PRIMARY );
1963 $idFallback = Sanitizer::escapeIdForAttribute(
'main/credits', Sanitizer::ID_FALLBACK );
1965 ' class="apihelp-header"',
1972 if ( $id !==
'main/credits' && $idFallback !==
'main/credits' ) {
1973 $headline =
'<div id="main/credits"></div>' . $headline;
1975 $help[
'credits'] .= $headline;
1976 $help[
'credits'] .= $this->
msg(
'api-credits' )->useDatabase(
false )->parseAsBlock();
1977 if ( !isset( $tocData[
'main/credits'] ) ) {
1978 $tocnumber[$level]++;
1979 $tocData[
'main/credits'] = [
1980 'toclevel' =>
count( $tocnumber ),
1982 'anchor' =>
'main/credits',
1984 'number' => implode(
'.', $tocnumber ),
1998 if ( !isset( $this->mCanApiHighLimits ) ) {
1999 $this->mCanApiHighLimits = $this->
getUser()->isAllowed(
'apihighlimits' );
2023 $this->
getRequest()->getHeader(
'Api-user-agent' ) .
' ' .
2024 $this->
getRequest()->getHeader(
'User-agent' )
getStatusValue()
Fetch the error status.
executeActionWithErrorHandling()
Execute an action, and in case of an error, erase whatever partial results have been accumulated,...
Library for creating and parsing MW-style timestamps.
This is the main API class, used for both external and internal processing.
getConfig()
Get the Config object.
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
WebRequest clone which takes values from a provided array.
Exception used to abort API execution with an error.
getContext()
Get the base IContextSource object.
checkReadOnly( $module)
Check if the DB is read-only for this user.
addWarning( $msg, $code=null, $data=null)
Add a warning for this module.
static sanitizeLangCode( $code)
Accepts a language code and ensures it's sane.
processing should stop and the error should be shown to the user * false
getParamsUsed()
Get the request parameters used in the course of the preceding execute() request.
static instance()
Singleton.
createErrorPrinter()
Create the printer for error output.
getErrorFormatter()
Get the ApiErrorFormatter object associated with current request.
getVal( $name, $default=null)
Get a request value, and register the fact that it was used, for logging.
wfGetLB( $wiki=false)
Get a load balancer object.
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
This manages continuation state.
dieWithError( $msg, $code=null, $data=null, $httpCode=null)
Abort execution with an error.
msg( $key)
Get a Message object with context set Parameters are the same as wfMessage()
sendCacheHeaders( $isError)
Send caching headers.
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
static $Modules
List of available modules: action name => module class.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
const PARAM_TYPE
(string|string[]) Either an array of allowed value strings, or a string type as described below.
logRequest( $time, $e=null)
Log the preceding request.
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
wfUrlencode( $s)
We want some things to be included as literal characters in our title URLs for prettiness,...
handleCORS()
Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
static handleApiBeforeMainException(Exception $e)
Handle an exception from the ApiBeforeMain hook.
checkConditionalRequestHeaders( $module)
Check selected RFC 7232 precondition headers.
dieWithErrorOrDebug( $msg, $code=null, $data=null, $httpCode=null)
Will only set a warning instead of failing if the global $wgDebugAPI is set to true.
lacksSameOriginSecurity()
Get the security flag for the current request.
wfHostname()
Fetch server name for use in error reporting etc.
wfReadOnly()
Check whether the wiki is in read-only mode.
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
const NO_SIZE_CHECK
For addValue() and similar functions, do not check size while adding a value Don't use this unless yo...
Allows to change the fields on the form that will be generated $name
getRequest()
Get the WebRequest object.
encodeRequestLogValue( $s)
Encode a value in a format suitable for a space-separated log line.
getUser()
Get the User object.
ApiContinuationManager null $mContinuationManager
static matchOrigin( $value, $rules, $exceptions)
Attempt to match an Origin header against a set of rules and a set of exceptions.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
static $mRights
List of user roles that are specifically relevant to the API.
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.
getLanguage()
Get the Language object.
static closeElement( $element)
Returns "</$element>".
getModule()
Get the API module object.
An IContextSource implementation which will inherit context from another source but allow individual ...
markParamsUsed( $params)
Mark parameters as used.
setupExecuteAction()
Set up for the execution.
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
This class represents the result of the API operations.
setContinuationManager( $manager)
Set the continuation manager.
This exception will be thrown when dieUsage is called to stop module execution.
bool null $lacksSameOriginSecurity
Cached return value from self::lacksSameOriginSecurity()
getOutput()
Get the OutputPage object.
static rollbackMasterChangesAndLog( $e)
Roll back any open database transactions and log the stack trace of the exception.
static makeHeadline( $level, $attribs, $anchor, $html, $link, $fallbackAnchor=false)
Create a headline for content.
getResult()
Get the ApiResult object associated with current request.
getSensitiveParams()
Get the request parameters that should be considered sensitive.
checkMaxLag( $module, $params)
Check the max lag if necessary.
const API_DEFAULT_USELANG
When no uselang parameter is given, this language will be used.
getExamplesMessages()
@inheritDoc
setCacheControl( $directives)
Set directives (key/value pairs) for the Cache-Control header.
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as $wgLang
getAllowedParams()
See ApiBase for description.
setupExternalResponse( $module, $params)
Check POST for external response and setup result printer.
see documentation in includes Linker php for Linker::makeImageLink & $time
createPrinterByName( $format)
Create an instance of an output formatter by its name.
getModuleManager()
Overrides to return this instance's module manager.
when a variable name is used in a it is silently declared as a new masking the global
static create( $msg, $code=null, array $data=null)
Create an IApiMessage for the message.
static matchRequestedHeaders( $requestedHeaders)
Attempt to validate the value of Access-Control-Request-Headers against a list of headers that we all...
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
addRequestedFields( $force=[])
Add requested fields to the result.
setContext(IContextSource $context)
Set the IContextSource object.
Interface for MediaWiki-localized exceptions.
canApiHighLimits()
Check whether the current user is allowed to use high limits.
checkBotReadOnly()
Check whether we are readonly for bots.
getContinuationManager()
Get the continuation manager.
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 class holds a list of modules and handles instantiation.
checkAsserts( $params)
Check asserts of the user's rights.
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
extractRequestParams( $parseLimit=true)
Using getAllowedParams(), this function makes an array of the values provided by the user,...
div flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException' returning false will NOT prevent logging $e
static appendDebugInfoToApiResult(IContextSource $context, ApiResult $result)
Append the debug info to given ApiResult.
wfClearOutputBuffers()
More legible than passing a 'false' parameter to wfResetOutputBuffers():
static wildcardToRegex( $wildcard)
Helper function to convert wildcard string into a regex '*' => '.
checkExecutePermissions( $module)
Check for sufficient permissions to execute.
addDeprecation( $msg, $feature, $data=[])
Add a deprecation warning for this module.
const LIMIT_SML2
Slow query, apihighlimits limit.
dieReadOnly()
Helper function for readonly errors.
__construct( $context=null, $enableWrite=false)
Constructs an instance of ApiMain that utilizes the module and format specified by $request.
reportUnusedParams()
Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,...
execute()
Execute api request.
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,...
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
static $Formats
List of available formats: format name => format class.
markParamsSensitive( $params)
Mark parameters as sensitive.
setRequestExpectations(ApiBase $module)
Set database connection, query, and write expectations given this module request.
substituteResultWithError( $e)
Replace the result data with the information about an exception.
static getMain()
Static methods.
getCheck( $name)
Get a boolean request value, and register the fact that the parameter was used, for logging.
printResult( $httpCode=0)
Print results using the current printer.
this hook is for auditing only $response
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
static isEveryoneAllowed( $right)
Check if all users may be assumed to have the given permission.
const LIMIT_BIG2
Fast query, apihighlimits limit.
const API_DEFAULT_FORMAT
When no format parameter is given, this format will be used.
const GETHEADER_LIST
Flag to make WebRequest::getHeader return an array of values.
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
getUpload( $name)
Get a request upload, and register the fact that it was used, for logging.
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
modifyHelp(array &$help, array $options, array &$tocData)
Called from ApiHelp before the pieces are joined together and returned.
static getRequestId()
Get the unique request ID.
static singleton( $wiki=false)
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
static openElement( $element, $attribs=[])
Identical to rawElement(), but has no third parameter and omits the end tag (and the self-closing '/'...
static rawElement( $element, $attribs=[], $contents='')
Returns an HTML element in a string.
executeAction()
Execute the actual module, without any error handling.
usually copyright or history_copyright This message must be in HTML not wikitext & $link
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
setupModule()
Set up the module for response.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
static factory( $code)
Get a cached or new language object for a given language code.
handleException(Exception $e)
Handle an exception as an API response.
static element( $element, $attribs=[], $contents='')
Identical to rawElement(), but HTML-escapes $contents (like Xml::element()).
isInternalMode()
Return true if the API was started by other PHP code using FauxRequest.
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 MediaWikiServices
getUserAgent()
Fetches the user agent used for this request.
setCacheMaxAge( $maxage)
Set how long the response should be cached.
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
errorMessagesFromException( $e, $type='error')
Create an error message for the given exception.
static getRedactedTraceAsString( $e)
Generate a string representation of an exception's stack trace.
setCacheMode( $mode)
Set the type of caching headers which will be sent.
getPrinter()
Get the result formatter object.
wfExpandUrl( $url, $defaultProto=PROTO_CURRENT)
Expand a potentially local URL to a fully-qualified URL.
the array() calling protocol came about after MediaWiki 1.4rc1.
static getGroupsWithPermission( $role)
Get all the groups who have a given permission.
this class mediates it Skin Encapsulates a look and feel for the wiki All of the functions that render HTML and make choices about how to render it are here and are called from various other places when and is meant to be subclassed with other skins that may override some of its functions The User object contains a reference to a and so rather than having a global skin object we just rely on the global User and get the skin with $wgUser and also has some character encoding functions and other locale stuff The current user interface language is instantiated as and the content language as $wgContLang
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 $out