5 * Created on Sep 4, 2006
7 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
29 * This is the main API class, used for both external and internal processing.
30 * When executed, it will create the requested formatter object,
31 * instantiate and execute an object associated with the needed action,
32 * and use formatter to print results.
33 * In case of an exception, an error message will be printed using the same formatter.
35 * To use API from another application, run it using FauxRequest object, in which
36 * case any internal exceptions will not be handled but passed up to the caller.
37 * After successful execution, use getResult() for the resulting data.
41 class ApiMain
extends ApiBase
{
43 * When no format parameter is given, this format will be used
45 const API_DEFAULT_FORMAT
= 'jsonfm';
48 * List of available modules: action name => module class
50 private static $Modules = [
51 'login' => 'ApiLogin',
52 'clientlogin' => 'ApiClientLogin',
53 'logout' => 'ApiLogout',
54 'createaccount' => 'ApiAMCreateAccount',
55 'linkaccount' => 'ApiLinkAccount',
56 'unlinkaccount' => 'ApiRemoveAuthenticationData',
57 'changeauthenticationdata' => 'ApiChangeAuthenticationData',
58 'removeauthenticationdata' => 'ApiRemoveAuthenticationData',
59 'resetpassword' => 'ApiResetPassword',
60 'query' => 'ApiQuery',
61 'expandtemplates' => 'ApiExpandTemplates',
62 'parse' => 'ApiParse',
63 'stashedit' => 'ApiStashEdit',
64 'opensearch' => 'ApiOpenSearch',
65 'feedcontributions' => 'ApiFeedContributions',
66 'feedrecentchanges' => 'ApiFeedRecentChanges',
67 'feedwatchlist' => 'ApiFeedWatchlist',
69 'paraminfo' => 'ApiParamInfo',
71 'compare' => 'ApiComparePages',
72 'tokens' => 'ApiTokens',
73 'checktoken' => 'ApiCheckToken',
76 'purge' => 'ApiPurge',
77 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
78 'rollback' => 'ApiRollback',
79 'delete' => 'ApiDelete',
80 'undelete' => 'ApiUndelete',
81 'protect' => 'ApiProtect',
82 'block' => 'ApiBlock',
83 'unblock' => 'ApiUnblock',
85 'edit' => 'ApiEditPage',
86 'upload' => 'ApiUpload',
87 'filerevert' => 'ApiFileRevert',
88 'emailuser' => 'ApiEmailUser',
89 'watch' => 'ApiWatch',
90 'patrol' => 'ApiPatrol',
91 'import' => 'ApiImport',
92 'clearhasmsg' => 'ApiClearHasMsg',
93 'userrights' => 'ApiUserrights',
94 'options' => 'ApiOptions',
95 'imagerotate' => 'ApiImageRotate',
96 'revisiondelete' => 'ApiRevisionDelete',
97 'managetags' => 'ApiManageTags',
99 'mergehistory' => 'ApiMergeHistory',
103 * List of available formats: format name => format class
105 private static $Formats = [
106 'json' => 'ApiFormatJson',
107 'jsonfm' => 'ApiFormatJson',
108 'php' => 'ApiFormatPhp',
109 'phpfm' => 'ApiFormatPhp',
110 'xml' => 'ApiFormatXml',
111 'xmlfm' => 'ApiFormatXml',
112 'rawfm' => 'ApiFormatJson',
113 'none' => 'ApiFormatNone',
116 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
118 * List of user roles that are specifically relevant to the API.
119 * array( 'right' => array ( 'msg' => 'Some message with a $1',
120 * 'params' => array ( $someVarToSubst ) ),
123 private static $mRights = [
125 'msg' => 'right-writeapi',
129 'msg' => 'api-help-right-apihighlimits',
130 'params' => [ ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
]
133 // @codingStandardsIgnoreEnd
140 private $mModuleMgr, $mResult, $mErrorFormatter, $mContinuationManager;
142 private $mEnableWrite;
143 private $mInternalMode, $mSquidMaxage;
147 private $mCacheMode = 'private';
148 private $mCacheControl = [];
149 private $mParamsUsed = [];
151 /** @var bool|null Cached return value from self::lacksSameOriginSecurity() */
152 private $lacksSameOriginSecurity = null;
155 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
157 * @param IContextSource|WebRequest $context If this is an instance of
158 * FauxRequest, errors are thrown and no printing occurs
159 * @param bool $enableWrite Should be set to true if the api may modify data
161 public function __construct( $context = null, $enableWrite = false ) {
162 if ( $context === null ) {
163 $context = RequestContext
::getMain();
164 } elseif ( $context instanceof WebRequest
) {
167 $context = RequestContext
::getMain();
169 // We set a derivative context so we can change stuff later
170 $this->setContext( new DerivativeContext( $context ) );
172 if ( isset( $request ) ) {
173 $this->getContext()->setRequest( $request );
176 $this->mInternalMode
= ( $this->getRequest() instanceof FauxRequest
);
178 // Special handling for the main module: $parent === $this
179 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
181 if ( !$this->mInternalMode
) {
182 // Impose module restrictions.
183 // If the current user cannot read,
184 // Remove all modules other than login
187 if ( $this->lacksSameOriginSecurity() ) {
188 // If we're in a mode that breaks the same-origin policy, strip
189 // user credentials for security.
190 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
191 $wgUser = new User();
192 $this->getContext()->setUser( $wgUser );
196 $uselang = $this->getParameter( 'uselang' );
197 if ( $uselang === 'user' ) {
198 // Assume the parent context is going to return the user language
199 // for uselang=user (see T85635).
201 if ( $uselang === 'content' ) {
203 $uselang = $wgContLang->getCode();
205 $code = RequestContext
::sanitizeLangCode( $uselang );
206 $this->getContext()->setLanguage( $code );
207 if ( !$this->mInternalMode
) {
209 $wgLang = $this->getContext()->getLanguage();
210 RequestContext
::getMain()->setLanguage( $wgLang );
214 $config = $this->getConfig();
215 $this->mModuleMgr
= new ApiModuleManager( $this );
216 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
217 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
218 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
219 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
221 Hooks
::run( 'ApiMain::moduleManager', [ $this->mModuleMgr
] );
223 $this->mResult
= new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
224 $this->mErrorFormatter
= new ApiErrorFormatter_BackCompat( $this->mResult
);
225 $this->mResult
->setErrorFormatter( $this->mErrorFormatter
);
226 $this->mResult
->setMainForContinuation( $this );
227 $this->mContinuationManager
= null;
228 $this->mEnableWrite
= $enableWrite;
230 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
231 $this->mCommit
= false;
235 * Return true if the API was started by other PHP code using FauxRequest
238 public function isInternalMode() {
239 return $this->mInternalMode
;
243 * Get the ApiResult object associated with current request
247 public function getResult() {
248 return $this->mResult
;
252 * Get the security flag for the current request
255 public function lacksSameOriginSecurity() {
256 if ( $this->lacksSameOriginSecurity
!== null ) {
257 return $this->lacksSameOriginSecurity
;
260 $request = $this->getRequest();
263 if ( $request->getVal( 'callback' ) !== null ) {
264 $this->lacksSameOriginSecurity
= true;
269 if ( $request->getVal( 'origin' ) === '*' ) {
270 $this->lacksSameOriginSecurity
= true;
274 // Header to be used from XMLHTTPRequest when the request might
275 // otherwise be used for XSS.
276 if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
277 $this->lacksSameOriginSecurity
= true;
281 // Allow extensions to override.
282 $this->lacksSameOriginSecurity
= !Hooks
::run( 'RequestHasSameOriginSecurity', [ $request ] );
283 return $this->lacksSameOriginSecurity
;
287 * Get the ApiErrorFormatter object associated with current request
288 * @return ApiErrorFormatter
290 public function getErrorFormatter() {
291 return $this->mErrorFormatter
;
295 * Get the continuation manager
296 * @return ApiContinuationManager|null
298 public function getContinuationManager() {
299 return $this->mContinuationManager
;
303 * Set the continuation manager
304 * @param ApiContinuationManager|null
306 public function setContinuationManager( $manager ) {
307 if ( $manager !== null ) {
308 if ( !$manager instanceof ApiContinuationManager
) {
309 throw new InvalidArgumentException( __METHOD__
. ': Was passed ' .
310 is_object( $manager ) ?
get_class( $manager ) : gettype( $manager )
313 if ( $this->mContinuationManager
!== null ) {
314 throw new UnexpectedValueException(
315 __METHOD__
. ': tried to set manager from ' . $manager->getSource() .
316 ' when a manager is already set from ' . $this->mContinuationManager
->getSource()
320 $this->mContinuationManager
= $manager;
324 * Get the API module object. Only works after executeAction()
328 public function getModule() {
329 return $this->mModule
;
333 * Get the result formatter object. Only works after setupExecuteAction()
335 * @return ApiFormatBase
337 public function getPrinter() {
338 return $this->mPrinter
;
342 * Set how long the response should be cached.
346 public function setCacheMaxAge( $maxage ) {
347 $this->setCacheControl( [
348 'max-age' => $maxage,
349 's-maxage' => $maxage
354 * Set the type of caching headers which will be sent.
356 * @param string $mode One of:
357 * - 'public': Cache this object in public caches, if the maxage or smaxage
358 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
359 * not provided by any of these means, the object will be private.
360 * - 'private': Cache this object only in private client-side caches.
361 * - 'anon-public-user-private': Make this object cacheable for logged-out
362 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
363 * set consistently for a given URL, it cannot be set differently depending on
364 * things like the contents of the database, or whether the user is logged in.
366 * If the wiki does not allow anonymous users to read it, the mode set here
367 * will be ignored, and private caching headers will always be sent. In other words,
368 * the "public" mode is equivalent to saying that the data sent is as public as a page
371 * For user-dependent data, the private mode should generally be used. The
372 * anon-public-user-private mode should only be used where there is a particularly
373 * good performance reason for caching the anonymous response, but where the
374 * response to logged-in users may differ, or may contain private data.
376 * If this function is never called, then the default will be the private mode.
378 public function setCacheMode( $mode ) {
379 if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
380 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
382 // Ignore for forwards-compatibility
386 if ( !User
::isEveryoneAllowed( 'read' ) ) {
387 // Private wiki, only private headers
388 if ( $mode !== 'private' ) {
389 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
395 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
396 // User language is used for i18n, so we don't want to publicly
397 // cache. Anons are ok, because if they have non-default language
398 // then there's an appropriate Vary header set by whatever set
399 // their non-default language.
400 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
401 "'anon-public-user-private' due to uselang=user\n" );
402 $mode = 'anon-public-user-private';
405 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
406 $this->mCacheMode
= $mode;
410 * Set directives (key/value pairs) for the Cache-Control header.
411 * Boolean values will be formatted as such, by including or omitting
412 * without an equals sign.
414 * Cache control values set here will only be used if the cache mode is not
415 * private, see setCacheMode().
417 * @param array $directives
419 public function setCacheControl( $directives ) {
420 $this->mCacheControl
= $directives +
$this->mCacheControl
;
424 * Create an instance of an output formatter by its name
426 * @param string $format
428 * @return ApiFormatBase
430 public function createPrinterByName( $format ) {
431 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
432 if ( $printer === null ) {
433 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
440 * Execute api request. Any errors will be handled if the API was called by the remote client.
442 public function execute() {
443 if ( $this->mInternalMode
) {
444 $this->executeAction();
446 $this->executeActionWithErrorHandling();
451 * Execute an action, and in case of an error, erase whatever partial results
452 * have been accumulated, and replace it with an error message and a help screen.
454 protected function executeActionWithErrorHandling() {
455 // Verify the CORS header before executing the action
456 if ( !$this->handleCORS() ) {
457 // handleCORS() has sent a 403, abort
461 // Exit here if the request method was OPTIONS
462 // (assume there will be a followup GET or POST)
463 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
467 // In case an error occurs during data output,
468 // clear the output buffer and print just the error information
469 $obLevel = ob_get_level();
472 $t = microtime( true );
475 $this->executeAction();
476 $runTime = microtime( true ) - $t;
477 $this->logRequest( $runTime );
478 if ( $this->mModule
->isWriteMode() && $this->getRequest()->wasPosted() ) {
479 $this->getStats()->timing(
480 'api.' . $this->mModule
->getModuleName() . '.executeTiming', 1000 * $runTime
483 } catch ( Exception
$e ) {
484 $this->handleException( $e );
485 $this->logRequest( microtime( true ) - $t, $e );
489 // Commit DBs and send any related cookies and headers
490 MediaWiki
::preOutputCommit( $this->getContext() );
492 // Send cache headers after any code which might generate an error, to
493 // avoid sending public cache headers for errors.
494 $this->sendCacheHeaders( $isError );
496 // Executing the action might have already messed with the output
498 while ( ob_get_level() > $obLevel ) {
504 * Handle an exception as an API response
507 * @param Exception $e
509 protected function handleException( Exception
$e ) {
510 // Bug 63145: Rollback any open database transactions
511 if ( !( $e instanceof UsageException
) ) {
512 // UsageExceptions are intentional, so don't rollback if that's the case
514 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
515 } catch ( DBError
$e2 ) {
516 // Rollback threw an exception too. Log it, but don't interrupt
517 // our regularly scheduled exception handling.
518 MWExceptionHandler
::logException( $e2 );
522 // Allow extra cleanup and logging
523 Hooks
::run( 'ApiMain::onException', [ $this, $e ] );
526 if ( !( $e instanceof UsageException
) ) {
527 MWExceptionHandler
::logException( $e );
530 // Handle any kind of exception by outputting properly formatted error message.
531 // If this fails, an unhandled exception should be thrown so that global error
532 // handler will process and log it.
534 $errCode = $this->substituteResultWithError( $e );
536 // Error results should not be cached
537 $this->setCacheMode( 'private' );
539 $response = $this->getRequest()->response();
540 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
541 if ( $e->getCode() === 0 ) {
542 $response->header( $headerStr );
544 $response->header( $headerStr, true, $e->getCode() );
547 // Reset and print just the error message
550 // Printer may not be initialized if the extractRequestParams() fails for the main module
551 $this->createErrorPrinter();
554 $this->printResult( true );
555 } catch ( UsageException
$ex ) {
556 // The error printer itself is failing. Try suppressing its request
557 // parameters and redo.
559 'Error printer failed (will retry without params): ' . $ex->getMessage()
561 $this->mPrinter
= null;
562 $this->createErrorPrinter();
563 $this->mPrinter
->forceDefaultParams();
564 $this->printResult( true );
569 * Handle an exception from the ApiBeforeMain hook.
571 * This tries to print the exception as an API response, to be more
572 * friendly to clients. If it fails, it will rethrow the exception.
575 * @param Exception $e
578 public static function handleApiBeforeMainException( Exception
$e ) {
582 $main = new self( RequestContext
::getMain(), false );
583 $main->handleException( $e );
584 $main->logRequest( 0, $e );
585 } catch ( Exception
$e2 ) {
586 // Nope, even that didn't work. Punt.
590 // Reset cache headers
591 $main->sendCacheHeaders( true );
597 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
599 * If no origin parameter is present, nothing happens.
600 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
601 * is set and false is returned.
602 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
603 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
605 * http://www.w3.org/TR/cors/#resource-requests
606 * http://www.w3.org/TR/cors/#resource-preflight-requests
608 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
610 protected function handleCORS() {
611 $originParam = $this->getParameter( 'origin' ); // defaults to null
612 if ( $originParam === null ) {
613 // No origin parameter, nothing to do
617 $request = $this->getRequest();
618 $response = $request->response();
620 $matchOrigin = false;
621 $allowTiming = false;
624 if ( $originParam === '*' ) {
625 // Request for anonymous CORS
628 $allowCredentials = 'false';
629 $varyOrigin = false; // No need to vary
631 // Non-anonymous CORS, check we allow the domain
633 // Origin: header is a space-separated list of origins, check all of them
634 $originHeader = $request->getHeader( 'Origin' );
635 if ( $originHeader === false ) {
638 $originHeader = trim( $originHeader );
639 $origins = preg_split( '/\s+/', $originHeader );
642 if ( !in_array( $originParam, $origins ) ) {
643 // origin parameter set but incorrect
644 // Send a 403 response
645 $response->statusHeader( 403 );
646 $response->header( 'Cache-Control: no-cache' );
647 echo "'origin' parameter does not match Origin header\n";
652 $config = $this->getConfig();
653 $matchOrigin = count( $origins ) === 1 && self
::matchOrigin(
655 $config->get( 'CrossSiteAJAXdomains' ),
656 $config->get( 'CrossSiteAJAXdomainExceptions' )
659 $allowOrigin = $originHeader;
660 $allowCredentials = 'true';
661 $allowTiming = $originHeader;
664 if ( $matchOrigin ) {
665 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
666 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
668 // This is a CORS preflight request
669 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
670 // If method is not a case-sensitive match, do not set any additional headers and terminate.
673 // We allow the actual request to send the following headers
674 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
675 if ( $requestedHeaders !== false ) {
676 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
679 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
682 // We only allow the actual request to be GET or POST
683 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
686 $response->header( "Access-Control-Allow-Origin: $allowOrigin" );
687 $response->header( "Access-Control-Allow-Credentials: $allowCredentials" );
688 // http://www.w3.org/TR/resource-timing/#timing-allow-origin
689 if ( $allowTiming !== false ) {
690 $response->header( "Timing-Allow-Origin: $allowTiming" );
695 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag'
701 $this->getOutput()->addVaryHeader( 'Origin' );
708 * Attempt to match an Origin header against a set of rules and a set of exceptions
709 * @param string $value Origin header
710 * @param array $rules Set of wildcard rules
711 * @param array $exceptions Set of wildcard rules
712 * @return bool True if $value matches a rule in $rules and doesn't match
713 * any rules in $exceptions, false otherwise
715 protected static function matchOrigin( $value, $rules, $exceptions ) {
716 foreach ( $rules as $rule ) {
717 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
718 // Rule matches, check exceptions
719 foreach ( $exceptions as $exc ) {
720 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
733 * Attempt to validate the value of Access-Control-Request-Headers against a list
734 * of headers that we allow the follow up request to send.
736 * @param string $requestedHeaders Comma seperated list of HTTP headers
737 * @return bool True if all requested headers are in the list of allowed headers
739 protected static function matchRequestedHeaders( $requestedHeaders ) {
740 if ( trim( $requestedHeaders ) === '' ) {
743 $requestedHeaders = explode( ',', $requestedHeaders );
744 $allowedAuthorHeaders = array_flip( [
745 /* simple headers (see spec) */
750 /* non-authorable headers in XHR, which are however requested by some UAs */
754 /* MediaWiki whitelist */
757 foreach ( $requestedHeaders as $rHeader ) {
758 $rHeader = strtolower( trim( $rHeader ) );
759 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
760 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
768 * Helper function to convert wildcard string into a regex
772 * @param string $wildcard String with wildcards
773 * @return string Regular expression
775 protected static function wildcardToRegex( $wildcard ) {
776 $wildcard = preg_quote( $wildcard, '/' );
777 $wildcard = str_replace(
783 return "/^https?:\/\/$wildcard$/";
787 * Send caching headers
788 * @param bool $isError Whether an error response is being output
789 * @since 1.26 added $isError parameter
791 protected function sendCacheHeaders( $isError ) {
792 $response = $this->getRequest()->response();
793 $out = $this->getOutput();
795 $out->addVaryHeader( 'Treat-as-Untrusted' );
797 $config = $this->getConfig();
799 if ( $config->get( 'VaryOnXFP' ) ) {
800 $out->addVaryHeader( 'X-Forwarded-Proto' );
803 if ( !$isError && $this->mModule
&&
804 ( $this->getRequest()->getMethod() === 'GET' ||
$this->getRequest()->getMethod() === 'HEAD' )
806 $etag = $this->mModule
->getConditionalRequestData( 'etag' );
807 if ( $etag !== null ) {
808 $response->header( "ETag: $etag" );
810 $lastMod = $this->mModule
->getConditionalRequestData( 'last-modified' );
811 if ( $lastMod !== null ) {
812 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $lastMod ) );
816 // The logic should be:
817 // $this->mCacheControl['max-age'] is set?
818 // Use it, the module knows better than our guess.
819 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
820 // Use 0 because we can guess caching is probably the wrong thing to do.
821 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
823 if ( isset( $this->mCacheControl
['max-age'] ) ) {
824 $maxage = $this->mCacheControl
['max-age'];
825 } elseif ( ( $this->mModule
&& !$this->mModule
->isWriteMode() ) ||
826 $this->mCacheMode
!== 'private'
828 $maxage = $this->getParameter( 'maxage' );
830 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
832 if ( $this->mCacheMode
== 'private' ) {
833 $response->header( "Cache-Control: $privateCache" );
837 $useKeyHeader = $config->get( 'UseKeyHeader' );
838 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
839 $out->addVaryHeader( 'Cookie' );
840 $response->header( $out->getVaryHeader() );
841 if ( $useKeyHeader ) {
842 $response->header( $out->getKeyHeader() );
843 if ( $out->haveCacheVaryCookies() ) {
844 // Logged in, mark this request private
845 $response->header( "Cache-Control: $privateCache" );
848 // Logged out, send normal public headers below
849 } elseif ( MediaWiki\Session\SessionManager
::getGlobalSession()->isPersistent() ) {
850 // Logged in or otherwise has session (e.g. anonymous users who have edited)
851 // Mark request private
852 $response->header( "Cache-Control: $privateCache" );
855 } // else no Key and anonymous, send public headers below
858 // Send public headers
859 $response->header( $out->getVaryHeader() );
860 if ( $useKeyHeader ) {
861 $response->header( $out->getKeyHeader() );
864 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
865 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
866 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
868 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
869 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
872 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
873 // Public cache not requested
874 // Sending a Vary header in this case is harmless, and protects us
875 // against conditional calls of setCacheMaxAge().
876 $response->header( "Cache-Control: $privateCache" );
881 $this->mCacheControl
['public'] = true;
883 // Send an Expires header
884 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
885 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
886 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
888 // Construct the Cache-Control header
891 foreach ( $this->mCacheControl
as $name => $value ) {
892 if ( is_bool( $value ) ) {
894 $ccHeader .= $separator . $name;
898 $ccHeader .= $separator . "$name=$value";
903 $response->header( "Cache-Control: $ccHeader" );
907 * Create the printer for error output
909 private function createErrorPrinter() {
910 if ( !isset( $this->mPrinter
) ) {
911 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
912 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
913 $value = self
::API_DEFAULT_FORMAT
;
915 $this->mPrinter
= $this->createPrinterByName( $value );
918 // Printer may not be able to handle errors. This is particularly
919 // likely if the module returns something for getCustomPrinter().
920 if ( !$this->mPrinter
->canPrintErrors() ) {
921 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
926 * Create an error message for the given exception.
928 * If the exception is a UsageException then
929 * UsageException::getMessageArray() will be called to create the message.
931 * @param Exception $e
932 * @return array ['code' => 'some string', 'info' => 'some other string']
935 protected function errorMessageFromException( $e ) {
936 if ( $e instanceof UsageException
) {
937 // User entered incorrect parameters - generate error response
938 $errMessage = $e->getMessageArray();
940 $config = $this->getConfig();
941 // Something is seriously wrong
942 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
943 $info = 'Database query error';
945 $info = "Exception Caught: {$e->getMessage()}";
949 'code' => 'internal_api_error_' . get_class( $e ),
950 'info' => '[' . WebRequest
::getRequestId() . '] ' . $info,
957 * Replace the result data with the information about an exception.
958 * Returns the error code
959 * @param Exception $e
962 protected function substituteResultWithError( $e ) {
963 $result = $this->getResult();
964 $config = $this->getConfig();
966 $errMessage = $this->errorMessageFromException( $e );
967 if ( $e instanceof UsageException
) {
968 // User entered incorrect parameters - generate error response
969 $link = wfExpandUrl( wfScript( 'api' ) );
970 ApiResult
::setContentValue( $errMessage, 'docref', "See $link for API usage" );
972 // Something is seriously wrong
973 if ( $config->get( 'ShowExceptionDetails' ) ) {
974 ApiResult
::setContentValue(
977 MWExceptionHandler
::getRedactedTraceAsString( $e )
982 // Remember all the warnings to re-add them later
983 $warnings = $result->getResultData( [ 'warnings' ] );
987 $requestid = $this->getParameter( 'requestid' );
988 if ( !is_null( $requestid ) ) {
989 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
991 if ( $config->get( 'ShowHostnames' ) ) {
992 // servedby is especially useful when debugging errors
993 $result->addValue( null, 'servedby', wfHostname(), ApiResult
::NO_SIZE_CHECK
);
995 if ( $warnings !== null ) {
996 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
999 $result->addValue( null, 'error', $errMessage, ApiResult
::NO_SIZE_CHECK
);
1001 return $errMessage['code'];
1005 * Set up for the execution.
1008 protected function setupExecuteAction() {
1009 // First add the id to the top element
1010 $result = $this->getResult();
1011 $requestid = $this->getParameter( 'requestid' );
1012 if ( !is_null( $requestid ) ) {
1013 $result->addValue( null, 'requestid', $requestid );
1016 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1017 $servedby = $this->getParameter( 'servedby' );
1019 $result->addValue( null, 'servedby', wfHostname() );
1023 if ( $this->getParameter( 'curtimestamp' ) ) {
1024 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
1025 ApiResult
::NO_SIZE_CHECK
);
1028 $params = $this->extractRequestParams();
1030 $this->mAction
= $params['action'];
1032 if ( !is_string( $this->mAction
) ) {
1033 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1040 * Set up the module for response
1041 * @return ApiBase The module that will handle this action
1042 * @throws MWException
1043 * @throws UsageException
1045 protected function setupModule() {
1046 // Instantiate the module requested by the user
1047 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
1048 if ( $module === null ) {
1049 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1051 $moduleParams = $module->extractRequestParams();
1053 // Check token, if necessary
1054 if ( $module->needsToken() === true ) {
1055 throw new MWException(
1056 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1057 'See documentation for ApiBase::needsToken for details.'
1060 if ( $module->needsToken() ) {
1061 if ( !$module->mustBePosted() ) {
1062 throw new MWException(
1063 "Module '{$module->getModuleName()}' must require POST to use tokens."
1067 if ( !isset( $moduleParams['token'] ) ) {
1068 $this->dieUsageMsg( [ 'missingparam', 'token' ] );
1071 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
1073 $module->encodeParamName( 'token' ),
1074 $this->getRequest()->getQueryValues()
1078 "The '{$module->encodeParamName( 'token' )}' parameter was " .
1079 'found in the query string, but must be in the POST body',
1084 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1085 $this->dieUsageMsg( 'sessionfailure' );
1093 * Check the max lag if necessary
1094 * @param ApiBase $module Api module being used
1095 * @param array $params Array an array containing the request parameters.
1096 * @return bool True on success, false should exit immediately
1098 protected function checkMaxLag( $module, $params ) {
1099 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1100 $maxLag = $params['maxlag'];
1101 list( $host, $lag ) = wfGetLB()->getMaxLag();
1102 if ( $lag > $maxLag ) {
1103 $response = $this->getRequest()->response();
1105 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1106 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
1108 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1109 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
1112 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
1120 * Check selected RFC 7232 precondition headers
1122 * RFC 7232 envisions a particular model where you send your request to "a
1123 * resource", and for write requests that you can read "the resource" by
1124 * changing the method to GET. When the API receives a GET request, it
1125 * works out even though "the resource" from RFC 7232's perspective might
1126 * be many resources from MediaWiki's perspective. But it totally fails for
1127 * a POST, since what HTTP sees as "the resource" is probably just
1128 * "/api.php" with all the interesting bits in the body.
1130 * Therefore, we only support RFC 7232 precondition headers for GET (and
1131 * HEAD). That means we don't need to bother with If-Match and
1132 * If-Unmodified-Since since they only apply to modification requests.
1134 * And since we don't support Range, If-Range is ignored too.
1137 * @param ApiBase $module Api module being used
1138 * @return bool True on success, false should exit immediately
1140 protected function checkConditionalRequestHeaders( $module ) {
1141 if ( $this->mInternalMode
) {
1142 // No headers to check in internal mode
1146 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1147 // Don't check POSTs
1153 $ifNoneMatch = array_diff(
1154 $this->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
) ?
: [],
1157 if ( $ifNoneMatch ) {
1158 if ( $ifNoneMatch === [ '*' ] ) {
1159 // API responses always "exist"
1162 $etag = $module->getConditionalRequestData( 'etag' );
1165 if ( $ifNoneMatch && $etag !== null ) {
1166 $test = substr( $etag, 0, 2 ) === 'W/' ?
substr( $etag, 2 ) : $etag;
1167 $match = array_map( function ( $s ) {
1168 return substr( $s, 0, 2 ) === 'W/' ?
substr( $s, 2 ) : $s;
1170 $return304 = in_array( $test, $match, true );
1172 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1174 // Some old browsers sends sizes after the date, like this:
1175 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1177 $i = strpos( $value, ';' );
1178 if ( $i !== false ) {
1179 $value = trim( substr( $value, 0, $i ) );
1182 if ( $value !== '' ) {
1184 $ts = new MWTimestamp( $value );
1186 // RFC 7231 IMF-fixdate
1187 $ts->getTimestamp( TS_RFC2822
) === $value ||
1189 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1190 // asctime (with and without space-padded day)
1191 $ts->format( 'D M j H:i:s Y' ) === $value ||
1192 $ts->format( 'D M j H:i:s Y' ) === $value
1194 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1195 if ( $lastMod !== null ) {
1196 // Mix in some MediaWiki modification times
1199 'user' => $this->getUser()->getTouched(),
1200 'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1202 if ( $this->getConfig()->get( 'UseSquid' ) ) {
1203 // T46570: the core page itself may not change, but resources might
1204 $modifiedTimes['sepoch'] = wfTimestamp(
1205 TS_MW
, time() - $this->getConfig()->get( 'SquidMaxage' )
1208 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1209 $lastMod = max( $modifiedTimes );
1210 $return304 = wfTimestamp( TS_MW
, $lastMod ) <= $ts->getTimestamp( TS_MW
);
1213 } catch ( TimestampException
$e ) {
1214 // Invalid timestamp, ignore it
1220 $this->getRequest()->response()->statusHeader( 304 );
1222 // Avoid outputting the compressed representation of a zero-length body
1223 MediaWiki\
suppressWarnings();
1224 ini_set( 'zlib.output_compression', 0 );
1225 MediaWiki\restoreWarnings
();
1226 wfClearOutputBuffers();
1235 * Check for sufficient permissions to execute
1236 * @param ApiBase $module An Api module
1238 protected function checkExecutePermissions( $module ) {
1239 $user = $this->getUser();
1240 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
1241 !$user->isAllowed( 'read' )
1243 $this->dieUsageMsg( 'readrequired' );
1246 if ( $module->isWriteMode() ) {
1247 if ( !$this->mEnableWrite
) {
1248 $this->dieUsageMsg( 'writedisabled' );
1249 } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1250 $this->dieUsageMsg( 'writerequired' );
1251 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1253 'Promise-Non-Write-API-Action HTTP header cannot be sent to write API modules',
1254 'promised-nonwrite-api'
1258 $this->checkReadOnly( $module );
1261 // Allow extensions to stop execution for arbitrary reasons.
1263 if ( !Hooks
::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1264 $this->dieUsageMsg( $message );
1269 * Check if the DB is read-only for this user
1270 * @param ApiBase $module An Api module
1272 protected function checkReadOnly( $module ) {
1273 if ( wfReadOnly() ) {
1274 $this->dieReadOnly();
1277 if ( $module->isWriteMode()
1278 && in_array( 'bot', $this->getUser()->getGroups() )
1279 && wfGetLB()->getServerCount() > 1
1281 $this->checkBotReadOnly();
1286 * Check whether we are readonly for bots
1288 private function checkBotReadOnly() {
1289 // Figure out how many servers have passed the lag threshold
1291 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1292 $laggedServers = [];
1293 $loadBalancer = wfGetLB();
1294 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1295 if ( $lag > $lagLimit ) {
1297 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1301 // If a majority of slaves are too lagged then disallow writes
1302 $slaveCount = wfGetLB()->getServerCount() - 1;
1303 if ( $numLagged >= ceil( $slaveCount / 2 ) ) {
1304 $laggedServers = implode( ', ', $laggedServers );
1307 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1310 $parsed = $this->parseMsg( [ 'readonlytext' ] );
1316 [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1322 * Check asserts of the user's rights
1323 * @param array $params
1325 protected function checkAsserts( $params ) {
1326 if ( isset( $params['assert'] ) ) {
1327 $user = $this->getUser();
1328 switch ( $params['assert'] ) {
1330 if ( $user->isAnon() ) {
1331 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
1335 if ( !$user->isAllowed( 'bot' ) ) {
1336 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1344 * Check POST for external response and setup result printer
1345 * @param ApiBase $module An Api module
1346 * @param array $params An array with the request parameters
1348 protected function setupExternalResponse( $module, $params ) {
1349 $request = $this->getRequest();
1350 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1351 // Module requires POST. GET request might still be allowed
1352 // if $wgDebugApi is true, otherwise fail.
1353 $this->dieUsageMsgOrDebug( [ 'mustbeposted', $this->mAction
] );
1356 // See if custom printer is used
1357 $this->mPrinter
= $module->getCustomPrinter();
1358 if ( is_null( $this->mPrinter
) ) {
1359 // Create an appropriate printer
1360 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1363 if ( $request->getProtocol() === 'http' && (
1364 $request->getSession()->shouldForceHTTPS() ||
1365 ( $this->getUser()->isLoggedIn() &&
1366 $this->getUser()->requiresHTTPS() )
1368 $this->logFeatureUsage( 'https-expected' );
1369 $this->setWarning( 'HTTP used when HTTPS was expected' );
1374 * Execute the actual module, without any error handling
1376 protected function executeAction() {
1377 $params = $this->setupExecuteAction();
1378 $module = $this->setupModule();
1379 $this->mModule
= $module;
1381 if ( !$this->mInternalMode
) {
1382 $this->setRequestExpectations( $module );
1385 $this->checkExecutePermissions( $module );
1387 if ( !$this->checkMaxLag( $module, $params ) ) {
1391 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1395 if ( !$this->mInternalMode
) {
1396 $this->setupExternalResponse( $module, $params );
1399 $this->checkAsserts( $params );
1403 Hooks
::run( 'APIAfterExecute', [ &$module ] );
1405 $this->reportUnusedParams();
1407 if ( !$this->mInternalMode
) {
1408 // append Debug information
1409 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1411 // Print result data
1412 $this->printResult( false );
1417 * Set database connection, query, and write expectations given this module request
1418 * @param ApiBase $module
1420 protected function setRequestExpectations( ApiBase
$module ) {
1421 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1422 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1423 if ( $this->getRequest()->hasSafeMethod() ) {
1424 $trxProfiler->setExpectations( $limits['GET'], __METHOD__
);
1425 } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1426 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__
);
1427 $this->getRequest()->markAsSafeRequest();
1429 $trxProfiler->setExpectations( $limits['POST'], __METHOD__
);
1434 * Log the preceding request
1435 * @param float $time Time in seconds
1436 * @param Exception $e Exception caught while processing the request
1438 protected function logRequest( $time, $e = null ) {
1439 $request = $this->getRequest();
1442 'ip' => $request->getIP(),
1443 'userAgent' => $this->getUserAgent(),
1444 'wiki' => wfWikiID(),
1445 'timeSpentBackend' => (int) round( $time * 1000 ),
1446 'hadError' => $e !== null,
1452 $logCtx['errorCodes'][] = $this->errorMessageFromException( $e )['code'];
1455 // Construct space separated message for 'api' log channel
1456 $msg = "API {$request->getMethod()} " .
1457 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1458 " {$logCtx['ip']} " .
1459 "T={$logCtx['timeSpentBackend']}ms";
1461 foreach ( $this->getParamsUsed() as $name ) {
1462 $value = $request->getVal( $name );
1463 if ( $value === null ) {
1467 if ( strlen( $value ) > 256 ) {
1468 $value = substr( $value, 0, 256 );
1469 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1471 $encValue = $this->encodeRequestLogValue( $value );
1474 $logCtx['params'][$name] = $value;
1475 $msg .= " {$name}={$encValue}";
1478 wfDebugLog( 'api', $msg, 'private' );
1479 // ApiAction channel is for structured data consumers
1480 wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1484 * Encode a value in a format suitable for a space-separated log line.
1488 protected function encodeRequestLogValue( $s ) {
1491 $chars = ';@$!*(),/:';
1492 $numChars = strlen( $chars );
1493 for ( $i = 0; $i < $numChars; $i++
) {
1494 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1498 return strtr( rawurlencode( $s ), $table );
1502 * Get the request parameters used in the course of the preceding execute() request
1505 protected function getParamsUsed() {
1506 return array_keys( $this->mParamsUsed
);
1510 * Mark parameters as used
1511 * @param string|string[] $params
1513 public function markParamsUsed( $params ) {
1514 $this->mParamsUsed +
= array_fill_keys( (array)$params, true );
1518 * Get a request value, and register the fact that it was used, for logging.
1519 * @param string $name
1520 * @param mixed $default
1523 public function getVal( $name, $default = null ) {
1524 $this->mParamsUsed
[$name] = true;
1526 $ret = $this->getRequest()->getVal( $name );
1527 if ( $ret === null ) {
1528 if ( $this->getRequest()->getArray( $name ) !== null ) {
1529 // See bug 10262 for why we don't just implode( '|', ... ) the
1532 "Parameter '$name' uses unsupported PHP array syntax"
1541 * Get a boolean request value, and register the fact that the parameter
1542 * was used, for logging.
1543 * @param string $name
1546 public function getCheck( $name ) {
1547 return $this->getVal( $name, null ) !== null;
1551 * Get a request upload, and register the fact that it was used, for logging.
1554 * @param string $name Parameter name
1555 * @return WebRequestUpload
1557 public function getUpload( $name ) {
1558 $this->mParamsUsed
[$name] = true;
1560 return $this->getRequest()->getUpload( $name );
1564 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1565 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1567 protected function reportUnusedParams() {
1568 $paramsUsed = $this->getParamsUsed();
1569 $allParams = $this->getRequest()->getValueNames();
1571 if ( !$this->mInternalMode
) {
1572 // Printer has not yet executed; don't warn that its parameters are unused
1573 $printerParams = array_map(
1574 [ $this->mPrinter
, 'encodeParamName' ],
1575 array_keys( $this->mPrinter
->getFinalParams() ?
: [] )
1577 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1579 $unusedParams = array_diff( $allParams, $paramsUsed );
1582 if ( count( $unusedParams ) ) {
1583 $s = count( $unusedParams ) > 1 ?
's' : '';
1584 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1589 * Print results using the current printer
1591 * @param bool $isError
1593 protected function printResult( $isError ) {
1594 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1595 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1598 $printer = $this->mPrinter
;
1599 $printer->initPrinter( false );
1600 $printer->execute();
1601 $printer->closePrinter();
1607 public function isReadMode() {
1612 * See ApiBase for description.
1616 public function getAllowedParams() {
1619 ApiBase
::PARAM_DFLT
=> 'help',
1620 ApiBase
::PARAM_TYPE
=> 'submodule',
1623 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1624 ApiBase
::PARAM_TYPE
=> 'submodule',
1627 ApiBase
::PARAM_TYPE
=> 'integer'
1630 ApiBase
::PARAM_TYPE
=> 'integer',
1631 ApiBase
::PARAM_DFLT
=> 0
1634 ApiBase
::PARAM_TYPE
=> 'integer',
1635 ApiBase
::PARAM_DFLT
=> 0
1638 ApiBase
::PARAM_TYPE
=> [ 'user', 'bot' ]
1640 'requestid' => null,
1641 'servedby' => false,
1642 'curtimestamp' => false,
1645 ApiBase
::PARAM_DFLT
=> 'user',
1650 /** @see ApiBase::getExamplesMessages() */
1651 protected function getExamplesMessages() {
1654 => 'apihelp-help-example-main',
1655 'action=help&recursivesubmodules=1'
1656 => 'apihelp-help-example-recursive',
1660 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1661 // Wish PHP had an "array_insert_before". Instead, we have to manually
1662 // reindex the array to get 'permissions' in the right place.
1665 foreach ( $oldHelp as $k => $v ) {
1666 if ( $k === 'submodules' ) {
1667 $help['permissions'] = '';
1671 $help['datatypes'] = '';
1672 $help['credits'] = '';
1674 // Fill 'permissions'
1675 $help['permissions'] .= Html
::openElement( 'div',
1676 [ 'class' => 'apihelp-block apihelp-permissions' ] );
1677 $m = $this->msg( 'api-help-permissions' );
1678 if ( !$m->isDisabled() ) {
1679 $help['permissions'] .= Html
::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1680 $m->numParams( count( self
::$mRights ) )->parse()
1683 $help['permissions'] .= Html
::openElement( 'dl' );
1684 foreach ( self
::$mRights as $right => $rightMsg ) {
1685 $help['permissions'] .= Html
::element( 'dt', null, $right );
1687 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1688 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1690 $groups = array_map( function ( $group ) {
1691 return $group == '*' ?
'all' : $group;
1692 }, User
::getGroupsWithPermission( $right ) );
1694 $help['permissions'] .= Html
::rawElement( 'dd', null,
1695 $this->msg( 'api-help-permissions-granted-to' )
1696 ->numParams( count( $groups ) )
1697 ->params( $this->getLanguage()->commaList( $groups ) )
1701 $help['permissions'] .= Html
::closeElement( 'dl' );
1702 $help['permissions'] .= Html
::closeElement( 'div' );
1704 // Fill 'datatypes' and 'credits', if applicable
1705 if ( empty( $options['nolead'] ) ) {
1706 $level = $options['headerlevel'];
1707 $tocnumber = &$options['tocnumber'];
1709 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1711 // Add an additional span with sanitized ID
1712 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1713 $header = Html
::element( 'span', [ 'id' => Sanitizer
::escapeId( 'main/datatypes' ) ] ) .
1716 $help['datatypes'] .= Html
::rawElement( 'h' . min( 6, $level ),
1717 [ 'id' => 'main/datatypes', 'class' => 'apihelp-header' ],
1720 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1721 if ( !isset( $tocData['main/datatypes'] ) ) {
1722 $tocnumber[$level]++
;
1723 $tocData['main/datatypes'] = [
1724 'toclevel' => count( $tocnumber ),
1726 'anchor' => 'main/datatypes',
1728 'number' => implode( '.', $tocnumber ),
1733 // Add an additional span with sanitized ID
1734 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1735 $header = Html
::element( 'span', [ 'id' => Sanitizer
::escapeId( 'main/credits' ) ] ) .
1738 $header = $this->msg( 'api-credits-header' )->parse();
1739 $help['credits'] .= Html
::rawElement( 'h' . min( 6, $level ),
1740 [ 'id' => 'main/credits', 'class' => 'apihelp-header' ],
1743 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1744 if ( !isset( $tocData['main/credits'] ) ) {
1745 $tocnumber[$level]++
;
1746 $tocData['main/credits'] = [
1747 'toclevel' => count( $tocnumber ),
1749 'anchor' => 'main/credits',
1751 'number' => implode( '.', $tocnumber ),
1758 private $mCanApiHighLimits = null;
1761 * Check whether the current user is allowed to use high limits
1764 public function canApiHighLimits() {
1765 if ( !isset( $this->mCanApiHighLimits
) ) {
1766 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1769 return $this->mCanApiHighLimits
;
1773 * Overrides to return this instance's module manager.
1774 * @return ApiModuleManager
1776 public function getModuleManager() {
1777 return $this->mModuleMgr
;
1781 * Fetches the user agent used for this request
1783 * The value will be the combination of the 'Api-User-Agent' header (if
1784 * any) and the standard User-Agent header (if any).
1788 public function getUserAgent() {
1790 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1791 $this->getRequest()->getHeader( 'User-agent' )
1795 /************************************************************************//**
1801 * Sets whether the pretty-printer should format *bold* and $italics$
1803 * @deprecated since 1.25
1806 public function setHelp( $help = true ) {
1807 wfDeprecated( __METHOD__
, '1.25' );
1808 $this->mPrinter
->setHelp( $help );
1812 * Override the parent to generate help messages for all available modules.
1814 * @deprecated since 1.25
1817 public function makeHelpMsg() {
1818 wfDeprecated( __METHOD__
, '1.25' );
1821 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1823 return ObjectCache
::getMainWANInstance()->getWithSetCallback(
1826 $this->getModuleName(),
1827 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) )
1829 $cacheHelpTimeout > 0 ?
$cacheHelpTimeout : WANObjectCache
::TTL_UNCACHEABLE
,
1830 [ $this, 'reallyMakeHelpMsg' ]
1835 * @deprecated since 1.25
1836 * @return mixed|string
1838 public function reallyMakeHelpMsg() {
1839 wfDeprecated( __METHOD__
, '1.25' );
1842 // Use parent to make default message for the main module
1843 $msg = parent
::makeHelpMsg();
1845 $asterisks = str_repeat( '*** ', 14 );
1846 $msg .= "\n\n$asterisks Modules $asterisks\n\n";
1848 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1849 $module = $this->mModuleMgr
->getModule( $name );
1850 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1852 $msg2 = $module->makeHelpMsg();
1853 if ( $msg2 !== false ) {
1859 $msg .= "\n$asterisks Permissions $asterisks\n\n";
1860 foreach ( self
::$mRights as $right => $rightMsg ) {
1861 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1862 ->useDatabase( false )
1863 ->inLanguage( 'en' )
1865 $groups = User
::getGroupsWithPermission( $right );
1866 $msg .= '* ' . $right . " *\n $rightsMsg" .
1867 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1870 $msg .= "\n$asterisks Formats $asterisks\n\n";
1871 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1872 $module = $this->mModuleMgr
->getModule( $name );
1873 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1874 $msg2 = $module->makeHelpMsg();
1875 if ( $msg2 !== false ) {
1881 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1882 $credits = str_replace( "\n", "\n ", $credits );
1883 $msg .= "\n*** Credits: ***\n $credits\n";
1889 * @deprecated since 1.25
1890 * @param ApiBase $module
1891 * @param string $paramName What type of request is this? e.g. action,
1892 * query, list, prop, meta, format
1895 public static function makeHelpMsgHeader( $module, $paramName ) {
1896 wfDeprecated( __METHOD__
, '1.25' );
1897 $modulePrefix = $module->getModulePrefix();
1898 if ( strval( $modulePrefix ) !== '' ) {
1899 $modulePrefix = "($modulePrefix) ";
1902 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1910 * This exception will be thrown when dieUsage is called to stop module execution.
1914 class UsageException
extends MWException
{
1921 private $mExtraData;
1924 * @param string $message
1925 * @param string $codestr
1927 * @param array|null $extradata
1929 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1930 parent
::__construct( $message, $code );
1931 $this->mCodestr
= $codestr;
1932 $this->mExtraData
= $extradata;
1938 public function getCodeString() {
1939 return $this->mCodestr
;
1945 public function getMessageArray() {
1947 'code' => $this->mCodestr
,
1948 'info' => $this->getMessage()
1950 if ( is_array( $this->mExtraData
) ) {
1951 $result = array_merge( $result, $this->mExtraData
);
1960 public function __toString() {
1961 return "{$this->getCodeString()}: {$this->getMessage()}";
1966 * For really cool vim folding this needs to be at the end:
1967 * vim: foldmarker=@{,@} foldmethod=marker