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 = [];
152 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
154 * @param IContextSource|WebRequest $context If this is an instance of
155 * FauxRequest, errors are thrown and no printing occurs
156 * @param bool $enableWrite Should be set to true if the api may modify data
158 public function __construct( $context = null, $enableWrite = false ) {
159 if ( $context === null ) {
160 $context = RequestContext
::getMain();
161 } elseif ( $context instanceof WebRequest
) {
164 $context = RequestContext
::getMain();
166 // We set a derivative context so we can change stuff later
167 $this->setContext( new DerivativeContext( $context ) );
169 if ( isset( $request ) ) {
170 $this->getContext()->setRequest( $request );
173 $this->mInternalMode
= ( $this->getRequest() instanceof FauxRequest
);
175 // Special handling for the main module: $parent === $this
176 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
178 if ( !$this->mInternalMode
) {
179 // Impose module restrictions.
180 // If the current user cannot read,
181 // Remove all modules other than login
184 if ( $this->lacksSameOriginSecurity() ) {
185 // If we're in a mode that breaks the same-origin policy, strip
186 // user credentials for security.
187 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
188 $wgUser = new User();
189 $this->getContext()->setUser( $wgUser );
193 $uselang = $this->getParameter( 'uselang' );
194 if ( $uselang === 'user' ) {
195 // Assume the parent context is going to return the user language
196 // for uselang=user (see T85635).
198 if ( $uselang === 'content' ) {
200 $uselang = $wgContLang->getCode();
202 $code = RequestContext
::sanitizeLangCode( $uselang );
203 $this->getContext()->setLanguage( $code );
204 if ( !$this->mInternalMode
) {
206 $wgLang = $this->getContext()->getLanguage();
207 RequestContext
::getMain()->setLanguage( $wgLang );
211 $config = $this->getConfig();
212 $this->mModuleMgr
= new ApiModuleManager( $this );
213 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
214 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
215 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
216 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
218 Hooks
::run( 'ApiMain::moduleManager', [ $this->mModuleMgr
] );
220 $this->mResult
= new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
221 $this->mErrorFormatter
= new ApiErrorFormatter_BackCompat( $this->mResult
);
222 $this->mResult
->setErrorFormatter( $this->mErrorFormatter
);
223 $this->mResult
->setMainForContinuation( $this );
224 $this->mContinuationManager
= null;
225 $this->mEnableWrite
= $enableWrite;
227 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
228 $this->mCommit
= false;
232 * Return true if the API was started by other PHP code using FauxRequest
235 public function isInternalMode() {
236 return $this->mInternalMode
;
240 * Get the ApiResult object associated with current request
244 public function getResult() {
245 return $this->mResult
;
249 * Get the ApiErrorFormatter object associated with current request
250 * @return ApiErrorFormatter
252 public function getErrorFormatter() {
253 return $this->mErrorFormatter
;
257 * Get the continuation manager
258 * @return ApiContinuationManager|null
260 public function getContinuationManager() {
261 return $this->mContinuationManager
;
265 * Set the continuation manager
266 * @param ApiContinuationManager|null
268 public function setContinuationManager( $manager ) {
269 if ( $manager !== null ) {
270 if ( !$manager instanceof ApiContinuationManager
) {
271 throw new InvalidArgumentException( __METHOD__
. ': Was passed ' .
272 is_object( $manager ) ?
get_class( $manager ) : gettype( $manager )
275 if ( $this->mContinuationManager
!== null ) {
276 throw new UnexpectedValueException(
277 __METHOD__
. ': tried to set manager from ' . $manager->getSource() .
278 ' when a manager is already set from ' . $this->mContinuationManager
->getSource()
282 $this->mContinuationManager
= $manager;
286 * Get the API module object. Only works after executeAction()
290 public function getModule() {
291 return $this->mModule
;
295 * Get the result formatter object. Only works after setupExecuteAction()
297 * @return ApiFormatBase
299 public function getPrinter() {
300 return $this->mPrinter
;
304 * Set how long the response should be cached.
308 public function setCacheMaxAge( $maxage ) {
309 $this->setCacheControl( [
310 'max-age' => $maxage,
311 's-maxage' => $maxage
316 * Set the type of caching headers which will be sent.
318 * @param string $mode One of:
319 * - 'public': Cache this object in public caches, if the maxage or smaxage
320 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
321 * not provided by any of these means, the object will be private.
322 * - 'private': Cache this object only in private client-side caches.
323 * - 'anon-public-user-private': Make this object cacheable for logged-out
324 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
325 * set consistently for a given URL, it cannot be set differently depending on
326 * things like the contents of the database, or whether the user is logged in.
328 * If the wiki does not allow anonymous users to read it, the mode set here
329 * will be ignored, and private caching headers will always be sent. In other words,
330 * the "public" mode is equivalent to saying that the data sent is as public as a page
333 * For user-dependent data, the private mode should generally be used. The
334 * anon-public-user-private mode should only be used where there is a particularly
335 * good performance reason for caching the anonymous response, but where the
336 * response to logged-in users may differ, or may contain private data.
338 * If this function is never called, then the default will be the private mode.
340 public function setCacheMode( $mode ) {
341 if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
342 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
344 // Ignore for forwards-compatibility
348 if ( !User
::isEveryoneAllowed( 'read' ) ) {
349 // Private wiki, only private headers
350 if ( $mode !== 'private' ) {
351 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
357 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
358 // User language is used for i18n, so we don't want to publicly
359 // cache. Anons are ok, because if they have non-default language
360 // then there's an appropriate Vary header set by whatever set
361 // their non-default language.
362 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
363 "'anon-public-user-private' due to uselang=user\n" );
364 $mode = 'anon-public-user-private';
367 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
368 $this->mCacheMode
= $mode;
372 * Set directives (key/value pairs) for the Cache-Control header.
373 * Boolean values will be formatted as such, by including or omitting
374 * without an equals sign.
376 * Cache control values set here will only be used if the cache mode is not
377 * private, see setCacheMode().
379 * @param array $directives
381 public function setCacheControl( $directives ) {
382 $this->mCacheControl
= $directives +
$this->mCacheControl
;
386 * Create an instance of an output formatter by its name
388 * @param string $format
390 * @return ApiFormatBase
392 public function createPrinterByName( $format ) {
393 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
394 if ( $printer === null ) {
395 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
402 * Execute api request. Any errors will be handled if the API was called by the remote client.
404 public function execute() {
405 if ( $this->mInternalMode
) {
406 $this->executeAction();
408 $this->executeActionWithErrorHandling();
413 * Execute an action, and in case of an error, erase whatever partial results
414 * have been accumulated, and replace it with an error message and a help screen.
416 protected function executeActionWithErrorHandling() {
417 // Verify the CORS header before executing the action
418 if ( !$this->handleCORS() ) {
419 // handleCORS() has sent a 403, abort
423 // Exit here if the request method was OPTIONS
424 // (assume there will be a followup GET or POST)
425 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
429 // In case an error occurs during data output,
430 // clear the output buffer and print just the error information
431 $obLevel = ob_get_level();
434 $t = microtime( true );
437 $this->executeAction();
438 $runTime = microtime( true ) - $t;
439 $this->logRequest( $runTime );
440 if ( $this->mModule
->isWriteMode() && $this->getRequest()->wasPosted() ) {
441 $this->getStats()->timing(
442 'api.' . $this->getModuleName() . '.executeTiming', 1000 * $runTime );
444 } catch ( Exception
$e ) {
445 $this->handleException( $e );
446 $this->logRequest( microtime( true ) - $t, $e );
450 // Commit DBs and send any related cookies and headers
451 MediaWiki
::preOutputCommit( $this->getContext() );
453 // Send cache headers after any code which might generate an error, to
454 // avoid sending public cache headers for errors.
455 $this->sendCacheHeaders( $isError );
457 // Executing the action might have already messed with the output
459 while ( ob_get_level() > $obLevel ) {
465 * Handle an exception as an API response
468 * @param Exception $e
470 protected function handleException( Exception
$e ) {
471 // Bug 63145: Rollback any open database transactions
472 if ( !( $e instanceof UsageException
) ) {
473 // UsageExceptions are intentional, so don't rollback if that's the case
475 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
476 } catch ( DBError
$e2 ) {
477 // Rollback threw an exception too. Log it, but don't interrupt
478 // our regularly scheduled exception handling.
479 MWExceptionHandler
::logException( $e2 );
483 // Allow extra cleanup and logging
484 Hooks
::run( 'ApiMain::onException', [ $this, $e ] );
487 if ( !( $e instanceof UsageException
) ) {
488 MWExceptionHandler
::logException( $e );
491 // Handle any kind of exception by outputting properly formatted error message.
492 // If this fails, an unhandled exception should be thrown so that global error
493 // handler will process and log it.
495 $errCode = $this->substituteResultWithError( $e );
497 // Error results should not be cached
498 $this->setCacheMode( 'private' );
500 $response = $this->getRequest()->response();
501 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
502 if ( $e->getCode() === 0 ) {
503 $response->header( $headerStr );
505 $response->header( $headerStr, true, $e->getCode() );
508 // Reset and print just the error message
511 // Printer may not be initialized if the extractRequestParams() fails for the main module
512 $this->createErrorPrinter();
515 $this->printResult( true );
516 } catch ( UsageException
$ex ) {
517 // The error printer itself is failing. Try suppressing its request
518 // parameters and redo.
520 'Error printer failed (will retry without params): ' . $ex->getMessage()
522 $this->mPrinter
= null;
523 $this->createErrorPrinter();
524 $this->mPrinter
->forceDefaultParams();
525 $this->printResult( true );
530 * Handle an exception from the ApiBeforeMain hook.
532 * This tries to print the exception as an API response, to be more
533 * friendly to clients. If it fails, it will rethrow the exception.
536 * @param Exception $e
539 public static function handleApiBeforeMainException( Exception
$e ) {
543 $main = new self( RequestContext
::getMain(), false );
544 $main->handleException( $e );
545 $main->logRequest( 0, $e );
546 } catch ( Exception
$e2 ) {
547 // Nope, even that didn't work. Punt.
551 // Reset cache headers
552 $main->sendCacheHeaders( true );
558 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
560 * If no origin parameter is present, nothing happens.
561 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
562 * is set and false is returned.
563 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
564 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
566 * http://www.w3.org/TR/cors/#resource-requests
567 * http://www.w3.org/TR/cors/#resource-preflight-requests
569 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
571 protected function handleCORS() {
572 $originParam = $this->getParameter( 'origin' ); // defaults to null
573 if ( $originParam === null ) {
574 // No origin parameter, nothing to do
578 $request = $this->getRequest();
579 $response = $request->response();
581 // Origin: header is a space-separated list of origins, check all of them
582 $originHeader = $request->getHeader( 'Origin' );
583 if ( $originHeader === false ) {
586 $originHeader = trim( $originHeader );
587 $origins = preg_split( '/\s+/', $originHeader );
590 if ( !in_array( $originParam, $origins ) ) {
591 // origin parameter set but incorrect
592 // Send a 403 response
593 $response->statusHeader( 403 );
594 $response->header( 'Cache-Control: no-cache' );
595 echo "'origin' parameter does not match Origin header\n";
600 $config = $this->getConfig();
601 $matchOrigin = count( $origins ) === 1 && self
::matchOrigin(
603 $config->get( 'CrossSiteAJAXdomains' ),
604 $config->get( 'CrossSiteAJAXdomainExceptions' )
607 if ( $matchOrigin ) {
608 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
609 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
611 // This is a CORS preflight request
612 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
613 // If method is not a case-sensitive match, do not set any additional headers and terminate.
616 // We allow the actual request to send the following headers
617 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
618 if ( $requestedHeaders !== false ) {
619 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
622 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
625 // We only allow the actual request to be GET or POST
626 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
629 $response->header( "Access-Control-Allow-Origin: $originHeader" );
630 $response->header( 'Access-Control-Allow-Credentials: true' );
631 // http://www.w3.org/TR/resource-timing/#timing-allow-origin
632 $response->header( "Timing-Allow-Origin: $originHeader" );
636 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag'
641 $this->getOutput()->addVaryHeader( 'Origin' );
646 * Attempt to match an Origin header against a set of rules and a set of exceptions
647 * @param string $value Origin header
648 * @param array $rules Set of wildcard rules
649 * @param array $exceptions Set of wildcard rules
650 * @return bool True if $value matches a rule in $rules and doesn't match
651 * any rules in $exceptions, false otherwise
653 protected static function matchOrigin( $value, $rules, $exceptions ) {
654 foreach ( $rules as $rule ) {
655 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
656 // Rule matches, check exceptions
657 foreach ( $exceptions as $exc ) {
658 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
671 * Attempt to validate the value of Access-Control-Request-Headers against a list
672 * of headers that we allow the follow up request to send.
674 * @param string $requestedHeaders Comma seperated list of HTTP headers
675 * @return bool True if all requested headers are in the list of allowed headers
677 protected static function matchRequestedHeaders( $requestedHeaders ) {
678 if ( trim( $requestedHeaders ) === '' ) {
681 $requestedHeaders = explode( ',', $requestedHeaders );
682 $allowedAuthorHeaders = array_flip( [
683 /* simple headers (see spec) */
688 /* non-authorable headers in XHR, which are however requested by some UAs */
692 /* MediaWiki whitelist */
695 foreach ( $requestedHeaders as $rHeader ) {
696 $rHeader = strtolower( trim( $rHeader ) );
697 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
698 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
706 * Helper function to convert wildcard string into a regex
710 * @param string $wildcard String with wildcards
711 * @return string Regular expression
713 protected static function wildcardToRegex( $wildcard ) {
714 $wildcard = preg_quote( $wildcard, '/' );
715 $wildcard = str_replace(
721 return "/^https?:\/\/$wildcard$/";
725 * Send caching headers
726 * @param bool $isError Whether an error response is being output
727 * @since 1.26 added $isError parameter
729 protected function sendCacheHeaders( $isError ) {
730 $response = $this->getRequest()->response();
731 $out = $this->getOutput();
733 $config = $this->getConfig();
735 if ( $config->get( 'VaryOnXFP' ) ) {
736 $out->addVaryHeader( 'X-Forwarded-Proto' );
739 if ( !$isError && $this->mModule
&&
740 ( $this->getRequest()->getMethod() === 'GET' ||
$this->getRequest()->getMethod() === 'HEAD' )
742 $etag = $this->mModule
->getConditionalRequestData( 'etag' );
743 if ( $etag !== null ) {
744 $response->header( "ETag: $etag" );
746 $lastMod = $this->mModule
->getConditionalRequestData( 'last-modified' );
747 if ( $lastMod !== null ) {
748 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $lastMod ) );
752 // The logic should be:
753 // $this->mCacheControl['max-age'] is set?
754 // Use it, the module knows better than our guess.
755 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
756 // Use 0 because we can guess caching is probably the wrong thing to do.
757 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
759 if ( isset( $this->mCacheControl
['max-age'] ) ) {
760 $maxage = $this->mCacheControl
['max-age'];
761 } elseif ( ( $this->mModule
&& !$this->mModule
->isWriteMode() ) ||
762 $this->mCacheMode
!== 'private'
764 $maxage = $this->getParameter( 'maxage' );
766 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
768 if ( $this->mCacheMode
== 'private' ) {
769 $response->header( "Cache-Control: $privateCache" );
773 $useKeyHeader = $config->get( 'UseKeyHeader' );
774 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
775 $out->addVaryHeader( 'Cookie' );
776 $response->header( $out->getVaryHeader() );
777 if ( $useKeyHeader ) {
778 $response->header( $out->getKeyHeader() );
779 if ( $out->haveCacheVaryCookies() ) {
780 // Logged in, mark this request private
781 $response->header( "Cache-Control: $privateCache" );
784 // Logged out, send normal public headers below
785 } elseif ( MediaWiki\Session\SessionManager
::getGlobalSession()->isPersistent() ) {
786 // Logged in or otherwise has session (e.g. anonymous users who have edited)
787 // Mark request private
788 $response->header( "Cache-Control: $privateCache" );
791 } // else no Key and anonymous, send public headers below
794 // Send public headers
795 $response->header( $out->getVaryHeader() );
796 if ( $useKeyHeader ) {
797 $response->header( $out->getKeyHeader() );
800 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
801 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
802 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
804 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
805 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
808 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
809 // Public cache not requested
810 // Sending a Vary header in this case is harmless, and protects us
811 // against conditional calls of setCacheMaxAge().
812 $response->header( "Cache-Control: $privateCache" );
817 $this->mCacheControl
['public'] = true;
819 // Send an Expires header
820 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
821 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
822 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
824 // Construct the Cache-Control header
827 foreach ( $this->mCacheControl
as $name => $value ) {
828 if ( is_bool( $value ) ) {
830 $ccHeader .= $separator . $name;
834 $ccHeader .= $separator . "$name=$value";
839 $response->header( "Cache-Control: $ccHeader" );
843 * Create the printer for error output
845 private function createErrorPrinter() {
846 if ( !isset( $this->mPrinter
) ) {
847 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
848 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
849 $value = self
::API_DEFAULT_FORMAT
;
851 $this->mPrinter
= $this->createPrinterByName( $value );
854 // Printer may not be able to handle errors. This is particularly
855 // likely if the module returns something for getCustomPrinter().
856 if ( !$this->mPrinter
->canPrintErrors() ) {
857 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
862 * Create an error message for the given exception.
864 * If the exception is a UsageException then
865 * UsageException::getMessageArray() will be called to create the message.
867 * @param Exception $e
868 * @return array ['code' => 'some string', 'info' => 'some other string']
871 protected function errorMessageFromException( $e ) {
872 if ( $e instanceof UsageException
) {
873 // User entered incorrect parameters - generate error response
874 $errMessage = $e->getMessageArray();
876 $config = $this->getConfig();
877 // Something is seriously wrong
878 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
879 $info = 'Database query error';
881 $info = "Exception Caught: {$e->getMessage()}";
885 'code' => 'internal_api_error_' . get_class( $e ),
886 'info' => '[' . WebRequest
::getRequestId() . '] ' . $info,
893 * Replace the result data with the information about an exception.
894 * Returns the error code
895 * @param Exception $e
898 protected function substituteResultWithError( $e ) {
899 $result = $this->getResult();
900 $config = $this->getConfig();
902 $errMessage = $this->errorMessageFromException( $e );
903 if ( $e instanceof UsageException
) {
904 // User entered incorrect parameters - generate error response
905 $link = wfExpandUrl( wfScript( 'api' ) );
906 ApiResult
::setContentValue( $errMessage, 'docref', "See $link for API usage" );
908 // Something is seriously wrong
909 if ( $config->get( 'ShowExceptionDetails' ) ) {
910 ApiResult
::setContentValue(
913 MWExceptionHandler
::getRedactedTraceAsString( $e )
918 // Remember all the warnings to re-add them later
919 $warnings = $result->getResultData( [ 'warnings' ] );
923 $requestid = $this->getParameter( 'requestid' );
924 if ( !is_null( $requestid ) ) {
925 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
927 if ( $config->get( 'ShowHostnames' ) ) {
928 // servedby is especially useful when debugging errors
929 $result->addValue( null, 'servedby', wfHostname(), ApiResult
::NO_SIZE_CHECK
);
931 if ( $warnings !== null ) {
932 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
935 $result->addValue( null, 'error', $errMessage, ApiResult
::NO_SIZE_CHECK
);
937 return $errMessage['code'];
941 * Set up for the execution.
944 protected function setupExecuteAction() {
945 // First add the id to the top element
946 $result = $this->getResult();
947 $requestid = $this->getParameter( 'requestid' );
948 if ( !is_null( $requestid ) ) {
949 $result->addValue( null, 'requestid', $requestid );
952 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
953 $servedby = $this->getParameter( 'servedby' );
955 $result->addValue( null, 'servedby', wfHostname() );
959 if ( $this->getParameter( 'curtimestamp' ) ) {
960 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
961 ApiResult
::NO_SIZE_CHECK
);
964 $params = $this->extractRequestParams();
966 $this->mAction
= $params['action'];
968 if ( !is_string( $this->mAction
) ) {
969 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
976 * Set up the module for response
977 * @return ApiBase The module that will handle this action
978 * @throws MWException
979 * @throws UsageException
981 protected function setupModule() {
982 // Instantiate the module requested by the user
983 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
984 if ( $module === null ) {
985 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
987 $moduleParams = $module->extractRequestParams();
989 // Check token, if necessary
990 if ( $module->needsToken() === true ) {
991 throw new MWException(
992 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
993 'See documentation for ApiBase::needsToken for details.'
996 if ( $module->needsToken() ) {
997 if ( !$module->mustBePosted() ) {
998 throw new MWException(
999 "Module '{$module->getModuleName()}' must require POST to use tokens."
1003 if ( !isset( $moduleParams['token'] ) ) {
1004 $this->dieUsageMsg( [ 'missingparam', 'token' ] );
1007 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
1009 $module->encodeParamName( 'token' ),
1010 $this->getRequest()->getQueryValues()
1014 "The '{$module->encodeParamName( 'token' )}' parameter was " .
1015 'found in the query string, but must be in the POST body',
1020 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1021 $this->dieUsageMsg( 'sessionfailure' );
1029 * Check the max lag if necessary
1030 * @param ApiBase $module Api module being used
1031 * @param array $params Array an array containing the request parameters.
1032 * @return bool True on success, false should exit immediately
1034 protected function checkMaxLag( $module, $params ) {
1035 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1036 $maxLag = $params['maxlag'];
1037 list( $host, $lag ) = wfGetLB()->getMaxLag();
1038 if ( $lag > $maxLag ) {
1039 $response = $this->getRequest()->response();
1041 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1042 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
1044 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1045 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
1048 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
1056 * Check selected RFC 7232 precondition headers
1058 * RFC 7232 envisions a particular model where you send your request to "a
1059 * resource", and for write requests that you can read "the resource" by
1060 * changing the method to GET. When the API receives a GET request, it
1061 * works out even though "the resource" from RFC 7232's perspective might
1062 * be many resources from MediaWiki's perspective. But it totally fails for
1063 * a POST, since what HTTP sees as "the resource" is probably just
1064 * "/api.php" with all the interesting bits in the body.
1066 * Therefore, we only support RFC 7232 precondition headers for GET (and
1067 * HEAD). That means we don't need to bother with If-Match and
1068 * If-Unmodified-Since since they only apply to modification requests.
1070 * And since we don't support Range, If-Range is ignored too.
1073 * @param ApiBase $module Api module being used
1074 * @return bool True on success, false should exit immediately
1076 protected function checkConditionalRequestHeaders( $module ) {
1077 if ( $this->mInternalMode
) {
1078 // No headers to check in internal mode
1082 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1083 // Don't check POSTs
1089 $ifNoneMatch = array_diff(
1090 $this->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
) ?
: [],
1093 if ( $ifNoneMatch ) {
1094 if ( $ifNoneMatch === [ '*' ] ) {
1095 // API responses always "exist"
1098 $etag = $module->getConditionalRequestData( 'etag' );
1101 if ( $ifNoneMatch && $etag !== null ) {
1102 $test = substr( $etag, 0, 2 ) === 'W/' ?
substr( $etag, 2 ) : $etag;
1103 $match = array_map( function ( $s ) {
1104 return substr( $s, 0, 2 ) === 'W/' ?
substr( $s, 2 ) : $s;
1106 $return304 = in_array( $test, $match, true );
1108 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1110 // Some old browsers sends sizes after the date, like this:
1111 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1113 $i = strpos( $value, ';' );
1114 if ( $i !== false ) {
1115 $value = trim( substr( $value, 0, $i ) );
1118 if ( $value !== '' ) {
1120 $ts = new MWTimestamp( $value );
1122 // RFC 7231 IMF-fixdate
1123 $ts->getTimestamp( TS_RFC2822
) === $value ||
1125 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1126 // asctime (with and without space-padded day)
1127 $ts->format( 'D M j H:i:s Y' ) === $value ||
1128 $ts->format( 'D M j H:i:s Y' ) === $value
1130 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1131 if ( $lastMod !== null ) {
1132 // Mix in some MediaWiki modification times
1135 'user' => $this->getUser()->getTouched(),
1136 'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1138 if ( $this->getConfig()->get( 'UseSquid' ) ) {
1139 // T46570: the core page itself may not change, but resources might
1140 $modifiedTimes['sepoch'] = wfTimestamp(
1141 TS_MW
, time() - $this->getConfig()->get( 'SquidMaxage' )
1144 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1145 $lastMod = max( $modifiedTimes );
1146 $return304 = wfTimestamp( TS_MW
, $lastMod ) <= $ts->getTimestamp( TS_MW
);
1149 } catch ( TimestampException
$e ) {
1150 // Invalid timestamp, ignore it
1156 $this->getRequest()->response()->statusHeader( 304 );
1158 // Avoid outputting the compressed representation of a zero-length body
1159 MediaWiki\
suppressWarnings();
1160 ini_set( 'zlib.output_compression', 0 );
1161 MediaWiki\restoreWarnings
();
1162 wfClearOutputBuffers();
1171 * Check for sufficient permissions to execute
1172 * @param ApiBase $module An Api module
1174 protected function checkExecutePermissions( $module ) {
1175 $user = $this->getUser();
1176 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
1177 !$user->isAllowed( 'read' )
1179 $this->dieUsageMsg( 'readrequired' );
1182 if ( $module->isWriteMode() ) {
1183 if ( !$this->mEnableWrite
) {
1184 $this->dieUsageMsg( 'writedisabled' );
1185 } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1186 $this->dieUsageMsg( 'writerequired' );
1187 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1189 'Promise-Non-Write-API-Action HTTP header cannot be sent to write API modules',
1190 'promised-nonwrite-api'
1194 $this->checkReadOnly( $module );
1197 // Allow extensions to stop execution for arbitrary reasons.
1199 if ( !Hooks
::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1200 $this->dieUsageMsg( $message );
1205 * Check if the DB is read-only for this user
1206 * @param ApiBase $module An Api module
1208 protected function checkReadOnly( $module ) {
1209 if ( wfReadOnly() ) {
1210 $this->dieReadOnly();
1213 if ( $module->isWriteMode()
1214 && in_array( 'bot', $this->getUser()->getGroups() )
1215 && wfGetLB()->getServerCount() > 1
1217 $this->checkBotReadOnly();
1222 * Check whether we are readonly for bots
1224 private function checkBotReadOnly() {
1225 // Figure out how many servers have passed the lag threshold
1227 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1228 $laggedServers = [];
1229 $loadBalancer = wfGetLB();
1230 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1231 if ( $lag > $lagLimit ) {
1233 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1237 // If a majority of slaves are too lagged then disallow writes
1238 $slaveCount = wfGetLB()->getServerCount() - 1;
1239 if ( $numLagged >= ceil( $slaveCount / 2 ) ) {
1240 $laggedServers = implode( ', ', $laggedServers );
1243 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1246 $parsed = $this->parseMsg( [ 'readonlytext' ] );
1252 [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1258 * Check asserts of the user's rights
1259 * @param array $params
1261 protected function checkAsserts( $params ) {
1262 if ( isset( $params['assert'] ) ) {
1263 $user = $this->getUser();
1264 switch ( $params['assert'] ) {
1266 if ( $user->isAnon() ) {
1267 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
1271 if ( !$user->isAllowed( 'bot' ) ) {
1272 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1280 * Check POST for external response and setup result printer
1281 * @param ApiBase $module An Api module
1282 * @param array $params An array with the request parameters
1284 protected function setupExternalResponse( $module, $params ) {
1285 $request = $this->getRequest();
1286 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1287 // Module requires POST. GET request might still be allowed
1288 // if $wgDebugApi is true, otherwise fail.
1289 $this->dieUsageMsgOrDebug( [ 'mustbeposted', $this->mAction
] );
1292 // See if custom printer is used
1293 $this->mPrinter
= $module->getCustomPrinter();
1294 if ( is_null( $this->mPrinter
) ) {
1295 // Create an appropriate printer
1296 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1299 if ( $request->getProtocol() === 'http' && (
1300 $request->getSession()->shouldForceHTTPS() ||
1301 ( $this->getUser()->isLoggedIn() &&
1302 $this->getUser()->requiresHTTPS() )
1304 $this->logFeatureUsage( 'https-expected' );
1305 $this->setWarning( 'HTTP used when HTTPS was expected' );
1310 * Execute the actual module, without any error handling
1312 protected function executeAction() {
1313 $params = $this->setupExecuteAction();
1314 $module = $this->setupModule();
1315 $this->mModule
= $module;
1317 if ( !$this->mInternalMode
) {
1318 $this->setRequestExpectations( $module );
1321 $this->checkExecutePermissions( $module );
1323 if ( !$this->checkMaxLag( $module, $params ) ) {
1327 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1331 if ( !$this->mInternalMode
) {
1332 $this->setupExternalResponse( $module, $params );
1335 $this->checkAsserts( $params );
1339 Hooks
::run( 'APIAfterExecute', [ &$module ] );
1341 $this->reportUnusedParams();
1343 if ( !$this->mInternalMode
) {
1344 // append Debug information
1345 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1347 // Print result data
1348 $this->printResult( false );
1353 * Set database connection, query, and write expectations given this module request
1354 * @param ApiBase $module
1356 protected function setRequestExpectations( ApiBase
$module ) {
1357 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1358 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1359 if ( $this->getRequest()->wasPosted() ) {
1360 if ( $module->isWriteMode() ) {
1361 $trxProfiler->setExpectations( $limits['POST'], __METHOD__
);
1363 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__
);
1364 $this->getRequest()->markAsSafeRequest();
1367 $trxProfiler->setExpectations( $limits['GET'], __METHOD__
);
1372 * Log the preceding request
1373 * @param float $time Time in seconds
1374 * @param Exception $e Exception caught while processing the request
1376 protected function logRequest( $time, $e = null ) {
1377 $request = $this->getRequest();
1380 'ip' => $request->getIP(),
1381 'userAgent' => $this->getUserAgent(),
1382 'wiki' => wfWikiID(),
1383 'timeSpentBackend' => (int) round( $time * 1000 ),
1384 'hadError' => $e !== null,
1390 $logCtx['errorCodes'][] = $this->errorMessageFromException( $e )['code'];
1393 // Construct space separated message for 'api' log channel
1394 $msg = "API {$request->getMethod()} " .
1395 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1396 " {$logCtx['ip']} " .
1397 "T={$logCtx['timeSpentBackend']}ms";
1399 foreach ( $this->getParamsUsed() as $name ) {
1400 $value = $request->getVal( $name );
1401 if ( $value === null ) {
1405 if ( strlen( $value ) > 256 ) {
1406 $value = substr( $value, 0, 256 );
1407 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1409 $encValue = $this->encodeRequestLogValue( $value );
1412 $logCtx['params'][$name] = $value;
1413 $msg .= " {$name}={$encValue}";
1416 wfDebugLog( 'api', $msg, 'private' );
1417 // ApiAction channel is for structured data consumers
1418 wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1422 * Encode a value in a format suitable for a space-separated log line.
1426 protected function encodeRequestLogValue( $s ) {
1429 $chars = ';@$!*(),/:';
1430 $numChars = strlen( $chars );
1431 for ( $i = 0; $i < $numChars; $i++
) {
1432 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1436 return strtr( rawurlencode( $s ), $table );
1440 * Get the request parameters used in the course of the preceding execute() request
1443 protected function getParamsUsed() {
1444 return array_keys( $this->mParamsUsed
);
1448 * Mark parameters as used
1449 * @param string|string[] $params
1451 public function markParamsUsed( $params ) {
1452 $this->mParamsUsed +
= array_fill_keys( (array)$params, true );
1456 * Get a request value, and register the fact that it was used, for logging.
1457 * @param string $name
1458 * @param mixed $default
1461 public function getVal( $name, $default = null ) {
1462 $this->mParamsUsed
[$name] = true;
1464 $ret = $this->getRequest()->getVal( $name );
1465 if ( $ret === null ) {
1466 if ( $this->getRequest()->getArray( $name ) !== null ) {
1467 // See bug 10262 for why we don't just implode( '|', ... ) the
1470 "Parameter '$name' uses unsupported PHP array syntax"
1479 * Get a boolean request value, and register the fact that the parameter
1480 * was used, for logging.
1481 * @param string $name
1484 public function getCheck( $name ) {
1485 return $this->getVal( $name, null ) !== null;
1489 * Get a request upload, and register the fact that it was used, for logging.
1492 * @param string $name Parameter name
1493 * @return WebRequestUpload
1495 public function getUpload( $name ) {
1496 $this->mParamsUsed
[$name] = true;
1498 return $this->getRequest()->getUpload( $name );
1502 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1503 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1505 protected function reportUnusedParams() {
1506 $paramsUsed = $this->getParamsUsed();
1507 $allParams = $this->getRequest()->getValueNames();
1509 if ( !$this->mInternalMode
) {
1510 // Printer has not yet executed; don't warn that its parameters are unused
1511 $printerParams = array_map(
1512 [ $this->mPrinter
, 'encodeParamName' ],
1513 array_keys( $this->mPrinter
->getFinalParams() ?
: [] )
1515 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1517 $unusedParams = array_diff( $allParams, $paramsUsed );
1520 if ( count( $unusedParams ) ) {
1521 $s = count( $unusedParams ) > 1 ?
's' : '';
1522 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1527 * Print results using the current printer
1529 * @param bool $isError
1531 protected function printResult( $isError ) {
1532 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1533 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1536 $printer = $this->mPrinter
;
1537 $printer->initPrinter( false );
1538 $printer->execute();
1539 $printer->closePrinter();
1545 public function isReadMode() {
1550 * See ApiBase for description.
1554 public function getAllowedParams() {
1557 ApiBase
::PARAM_DFLT
=> 'help',
1558 ApiBase
::PARAM_TYPE
=> 'submodule',
1561 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1562 ApiBase
::PARAM_TYPE
=> 'submodule',
1565 ApiBase
::PARAM_TYPE
=> 'integer'
1568 ApiBase
::PARAM_TYPE
=> 'integer',
1569 ApiBase
::PARAM_DFLT
=> 0
1572 ApiBase
::PARAM_TYPE
=> 'integer',
1573 ApiBase
::PARAM_DFLT
=> 0
1576 ApiBase
::PARAM_TYPE
=> [ 'user', 'bot' ]
1578 'requestid' => null,
1579 'servedby' => false,
1580 'curtimestamp' => false,
1583 ApiBase
::PARAM_DFLT
=> 'user',
1588 /** @see ApiBase::getExamplesMessages() */
1589 protected function getExamplesMessages() {
1592 => 'apihelp-help-example-main',
1593 'action=help&recursivesubmodules=1'
1594 => 'apihelp-help-example-recursive',
1598 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1599 // Wish PHP had an "array_insert_before". Instead, we have to manually
1600 // reindex the array to get 'permissions' in the right place.
1603 foreach ( $oldHelp as $k => $v ) {
1604 if ( $k === 'submodules' ) {
1605 $help['permissions'] = '';
1609 $help['datatypes'] = '';
1610 $help['credits'] = '';
1612 // Fill 'permissions'
1613 $help['permissions'] .= Html
::openElement( 'div',
1614 [ 'class' => 'apihelp-block apihelp-permissions' ] );
1615 $m = $this->msg( 'api-help-permissions' );
1616 if ( !$m->isDisabled() ) {
1617 $help['permissions'] .= Html
::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1618 $m->numParams( count( self
::$mRights ) )->parse()
1621 $help['permissions'] .= Html
::openElement( 'dl' );
1622 foreach ( self
::$mRights as $right => $rightMsg ) {
1623 $help['permissions'] .= Html
::element( 'dt', null, $right );
1625 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1626 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1628 $groups = array_map( function ( $group ) {
1629 return $group == '*' ?
'all' : $group;
1630 }, User
::getGroupsWithPermission( $right ) );
1632 $help['permissions'] .= Html
::rawElement( 'dd', null,
1633 $this->msg( 'api-help-permissions-granted-to' )
1634 ->numParams( count( $groups ) )
1635 ->params( $this->getLanguage()->commaList( $groups ) )
1639 $help['permissions'] .= Html
::closeElement( 'dl' );
1640 $help['permissions'] .= Html
::closeElement( 'div' );
1642 // Fill 'datatypes' and 'credits', if applicable
1643 if ( empty( $options['nolead'] ) ) {
1644 $level = $options['headerlevel'];
1645 $tocnumber = &$options['tocnumber'];
1647 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1648 $help['datatypes'] .= Html
::rawElement( 'h' . min( 6, $level ),
1649 [ 'id' => 'main/datatypes', 'class' => 'apihelp-header' ],
1650 Html
::element( 'span', [ 'id' => Sanitizer
::escapeId( 'main/datatypes' ) ] ) .
1653 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1654 if ( !isset( $tocData['main/datatypes'] ) ) {
1655 $tocnumber[$level]++
;
1656 $tocData['main/datatypes'] = [
1657 'toclevel' => count( $tocnumber ),
1659 'anchor' => 'main/datatypes',
1661 'number' => implode( '.', $tocnumber ),
1666 $header = $this->msg( 'api-credits-header' )->parse();
1667 $help['credits'] .= Html
::rawElement( 'h' . min( 6, $level ),
1668 [ 'id' => 'main/credits', 'class' => 'apihelp-header' ],
1669 Html
::element( 'span', [ 'id' => Sanitizer
::escapeId( 'main/credits' ) ] ) .
1672 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1673 if ( !isset( $tocData['main/credits'] ) ) {
1674 $tocnumber[$level]++
;
1675 $tocData['main/credits'] = [
1676 'toclevel' => count( $tocnumber ),
1678 'anchor' => 'main/credits',
1680 'number' => implode( '.', $tocnumber ),
1687 private $mCanApiHighLimits = null;
1690 * Check whether the current user is allowed to use high limits
1693 public function canApiHighLimits() {
1694 if ( !isset( $this->mCanApiHighLimits
) ) {
1695 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1698 return $this->mCanApiHighLimits
;
1702 * Overrides to return this instance's module manager.
1703 * @return ApiModuleManager
1705 public function getModuleManager() {
1706 return $this->mModuleMgr
;
1710 * Fetches the user agent used for this request
1712 * The value will be the combination of the 'Api-User-Agent' header (if
1713 * any) and the standard User-Agent header (if any).
1717 public function getUserAgent() {
1719 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1720 $this->getRequest()->getHeader( 'User-agent' )
1724 /************************************************************************//**
1730 * Sets whether the pretty-printer should format *bold* and $italics$
1732 * @deprecated since 1.25
1735 public function setHelp( $help = true ) {
1736 wfDeprecated( __METHOD__
, '1.25' );
1737 $this->mPrinter
->setHelp( $help );
1741 * Override the parent to generate help messages for all available modules.
1743 * @deprecated since 1.25
1746 public function makeHelpMsg() {
1747 wfDeprecated( __METHOD__
, '1.25' );
1750 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1752 return ObjectCache
::getMainWANInstance()->getWithSetCallback(
1755 $this->getModuleName(),
1756 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) )
1758 $cacheHelpTimeout > 0 ?
$cacheHelpTimeout : WANObjectCache
::TTL_UNCACHEABLE
,
1759 [ $this, 'reallyMakeHelpMsg' ]
1764 * @deprecated since 1.25
1765 * @return mixed|string
1767 public function reallyMakeHelpMsg() {
1768 wfDeprecated( __METHOD__
, '1.25' );
1771 // Use parent to make default message for the main module
1772 $msg = parent
::makeHelpMsg();
1774 $asterisks = str_repeat( '*** ', 14 );
1775 $msg .= "\n\n$asterisks Modules $asterisks\n\n";
1777 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1778 $module = $this->mModuleMgr
->getModule( $name );
1779 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1781 $msg2 = $module->makeHelpMsg();
1782 if ( $msg2 !== false ) {
1788 $msg .= "\n$asterisks Permissions $asterisks\n\n";
1789 foreach ( self
::$mRights as $right => $rightMsg ) {
1790 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1791 ->useDatabase( false )
1792 ->inLanguage( 'en' )
1794 $groups = User
::getGroupsWithPermission( $right );
1795 $msg .= '* ' . $right . " *\n $rightsMsg" .
1796 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1799 $msg .= "\n$asterisks Formats $asterisks\n\n";
1800 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1801 $module = $this->mModuleMgr
->getModule( $name );
1802 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1803 $msg2 = $module->makeHelpMsg();
1804 if ( $msg2 !== false ) {
1810 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1811 $credits = str_replace( "\n", "\n ", $credits );
1812 $msg .= "\n*** Credits: ***\n $credits\n";
1818 * @deprecated since 1.25
1819 * @param ApiBase $module
1820 * @param string $paramName What type of request is this? e.g. action,
1821 * query, list, prop, meta, format
1824 public static function makeHelpMsgHeader( $module, $paramName ) {
1825 wfDeprecated( __METHOD__
, '1.25' );
1826 $modulePrefix = $module->getModulePrefix();
1827 if ( strval( $modulePrefix ) !== '' ) {
1828 $modulePrefix = "($modulePrefix) ";
1831 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1839 * This exception will be thrown when dieUsage is called to stop module execution.
1843 class UsageException
extends MWException
{
1850 private $mExtraData;
1853 * @param string $message
1854 * @param string $codestr
1856 * @param array|null $extradata
1858 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1859 parent
::__construct( $message, $code );
1860 $this->mCodestr
= $codestr;
1861 $this->mExtraData
= $extradata;
1867 public function getCodeString() {
1868 return $this->mCodestr
;
1874 public function getMessageArray() {
1876 'code' => $this->mCodestr
,
1877 'info' => $this->getMessage()
1879 if ( is_array( $this->mExtraData
) ) {
1880 $result = array_merge( $result, $this->mExtraData
);
1889 public function __toString() {
1890 return "{$this->getCodeString()}: {$this->getMessage()}";
1895 * For really cool vim folding this needs to be at the end:
1896 * vim: foldmarker=@{,@} foldmethod=marker