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 'logout' => 'ApiLogout',
53 'createaccount' => 'ApiCreateAccount',
54 'query' => 'ApiQuery',
55 'expandtemplates' => 'ApiExpandTemplates',
56 'parse' => 'ApiParse',
57 'stashedit' => 'ApiStashEdit',
58 'opensearch' => 'ApiOpenSearch',
59 'feedcontributions' => 'ApiFeedContributions',
60 'feedrecentchanges' => 'ApiFeedRecentChanges',
61 'feedwatchlist' => 'ApiFeedWatchlist',
63 'paraminfo' => 'ApiParamInfo',
65 'compare' => 'ApiComparePages',
66 'tokens' => 'ApiTokens',
67 'checktoken' => 'ApiCheckToken',
70 'purge' => 'ApiPurge',
71 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
72 'rollback' => 'ApiRollback',
73 'delete' => 'ApiDelete',
74 'undelete' => 'ApiUndelete',
75 'protect' => 'ApiProtect',
76 'block' => 'ApiBlock',
77 'unblock' => 'ApiUnblock',
79 'edit' => 'ApiEditPage',
80 'upload' => 'ApiUpload',
81 'filerevert' => 'ApiFileRevert',
82 'emailuser' => 'ApiEmailUser',
83 'watch' => 'ApiWatch',
84 'patrol' => 'ApiPatrol',
85 'import' => 'ApiImport',
86 'clearhasmsg' => 'ApiClearHasMsg',
87 'userrights' => 'ApiUserrights',
88 'options' => 'ApiOptions',
89 'imagerotate' => 'ApiImageRotate',
90 'revisiondelete' => 'ApiRevisionDelete',
91 'managetags' => 'ApiManageTags',
93 'mergehistory' => 'ApiMergeHistory',
97 * List of available formats: format name => format class
99 private static $Formats = [
100 'json' => 'ApiFormatJson',
101 'jsonfm' => 'ApiFormatJson',
102 'php' => 'ApiFormatPhp',
103 'phpfm' => 'ApiFormatPhp',
104 'xml' => 'ApiFormatXml',
105 'xmlfm' => 'ApiFormatXml',
106 'rawfm' => 'ApiFormatJson',
107 'none' => 'ApiFormatNone',
110 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
112 * List of user roles that are specifically relevant to the API.
113 * array( 'right' => array ( 'msg' => 'Some message with a $1',
114 * 'params' => array ( $someVarToSubst ) ),
117 private static $mRights = [
119 'msg' => 'right-writeapi',
123 'msg' => 'api-help-right-apihighlimits',
124 'params' => [ ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
]
127 // @codingStandardsIgnoreEnd
134 private $mModuleMgr, $mResult, $mErrorFormatter, $mContinuationManager;
136 private $mEnableWrite;
137 private $mInternalMode, $mSquidMaxage;
141 private $mCacheMode = 'private';
142 private $mCacheControl = [];
143 private $mParamsUsed = [];
146 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
148 * @param IContextSource|WebRequest $context If this is an instance of
149 * FauxRequest, errors are thrown and no printing occurs
150 * @param bool $enableWrite Should be set to true if the api may modify data
152 public function __construct( $context = null, $enableWrite = false ) {
153 if ( $context === null ) {
154 $context = RequestContext
::getMain();
155 } elseif ( $context instanceof WebRequest
) {
158 $context = RequestContext
::getMain();
160 // We set a derivative context so we can change stuff later
161 $this->setContext( new DerivativeContext( $context ) );
163 if ( isset( $request ) ) {
164 $this->getContext()->setRequest( $request );
167 $this->mInternalMode
= ( $this->getRequest() instanceof FauxRequest
);
169 // Special handling for the main module: $parent === $this
170 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
172 if ( !$this->mInternalMode
) {
173 // Impose module restrictions.
174 // If the current user cannot read,
175 // Remove all modules other than login
178 if ( $this->lacksSameOriginSecurity() ) {
179 // If we're in a mode that breaks the same-origin policy, strip
180 // user credentials for security.
181 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
182 $wgUser = new User();
183 $this->getContext()->setUser( $wgUser );
187 $uselang = $this->getParameter( 'uselang' );
188 if ( $uselang === 'user' ) {
189 // Assume the parent context is going to return the user language
190 // for uselang=user (see T85635).
192 if ( $uselang === 'content' ) {
194 $uselang = $wgContLang->getCode();
196 $code = RequestContext
::sanitizeLangCode( $uselang );
197 $this->getContext()->setLanguage( $code );
198 if ( !$this->mInternalMode
) {
200 $wgLang = $this->getContext()->getLanguage();
201 RequestContext
::getMain()->setLanguage( $wgLang );
205 $config = $this->getConfig();
206 $this->mModuleMgr
= new ApiModuleManager( $this );
207 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
208 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
209 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
210 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
212 Hooks
::run( 'ApiMain::moduleManager', [ $this->mModuleMgr
] );
214 $this->mResult
= new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
215 $this->mErrorFormatter
= new ApiErrorFormatter_BackCompat( $this->mResult
);
216 $this->mResult
->setErrorFormatter( $this->mErrorFormatter
);
217 $this->mResult
->setMainForContinuation( $this );
218 $this->mContinuationManager
= null;
219 $this->mEnableWrite
= $enableWrite;
221 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
222 $this->mCommit
= false;
226 * Return true if the API was started by other PHP code using FauxRequest
229 public function isInternalMode() {
230 return $this->mInternalMode
;
234 * Get the ApiResult object associated with current request
238 public function getResult() {
239 return $this->mResult
;
243 * Get the ApiErrorFormatter object associated with current request
244 * @return ApiErrorFormatter
246 public function getErrorFormatter() {
247 return $this->mErrorFormatter
;
251 * Get the continuation manager
252 * @return ApiContinuationManager|null
254 public function getContinuationManager() {
255 return $this->mContinuationManager
;
259 * Set the continuation manager
260 * @param ApiContinuationManager|null
262 public function setContinuationManager( $manager ) {
263 if ( $manager !== null ) {
264 if ( !$manager instanceof ApiContinuationManager
) {
265 throw new InvalidArgumentException( __METHOD__
. ': Was passed ' .
266 is_object( $manager ) ?
get_class( $manager ) : gettype( $manager )
269 if ( $this->mContinuationManager
!== null ) {
270 throw new UnexpectedValueException(
271 __METHOD__
. ': tried to set manager from ' . $manager->getSource() .
272 ' when a manager is already set from ' . $this->mContinuationManager
->getSource()
276 $this->mContinuationManager
= $manager;
280 * Get the API module object. Only works after executeAction()
284 public function getModule() {
285 return $this->mModule
;
289 * Get the result formatter object. Only works after setupExecuteAction()
291 * @return ApiFormatBase
293 public function getPrinter() {
294 return $this->mPrinter
;
298 * Set how long the response should be cached.
302 public function setCacheMaxAge( $maxage ) {
303 $this->setCacheControl( [
304 'max-age' => $maxage,
305 's-maxage' => $maxage
310 * Set the type of caching headers which will be sent.
312 * @param string $mode One of:
313 * - 'public': Cache this object in public caches, if the maxage or smaxage
314 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
315 * not provided by any of these means, the object will be private.
316 * - 'private': Cache this object only in private client-side caches.
317 * - 'anon-public-user-private': Make this object cacheable for logged-out
318 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
319 * set consistently for a given URL, it cannot be set differently depending on
320 * things like the contents of the database, or whether the user is logged in.
322 * If the wiki does not allow anonymous users to read it, the mode set here
323 * will be ignored, and private caching headers will always be sent. In other words,
324 * the "public" mode is equivalent to saying that the data sent is as public as a page
327 * For user-dependent data, the private mode should generally be used. The
328 * anon-public-user-private mode should only be used where there is a particularly
329 * good performance reason for caching the anonymous response, but where the
330 * response to logged-in users may differ, or may contain private data.
332 * If this function is never called, then the default will be the private mode.
334 public function setCacheMode( $mode ) {
335 if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
336 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
338 // Ignore for forwards-compatibility
342 if ( !User
::isEveryoneAllowed( 'read' ) ) {
343 // Private wiki, only private headers
344 if ( $mode !== 'private' ) {
345 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
351 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
352 // User language is used for i18n, so we don't want to publicly
353 // cache. Anons are ok, because if they have non-default language
354 // then there's an appropriate Vary header set by whatever set
355 // their non-default language.
356 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
357 "'anon-public-user-private' due to uselang=user\n" );
358 $mode = 'anon-public-user-private';
361 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
362 $this->mCacheMode
= $mode;
366 * Set directives (key/value pairs) for the Cache-Control header.
367 * Boolean values will be formatted as such, by including or omitting
368 * without an equals sign.
370 * Cache control values set here will only be used if the cache mode is not
371 * private, see setCacheMode().
373 * @param array $directives
375 public function setCacheControl( $directives ) {
376 $this->mCacheControl
= $directives +
$this->mCacheControl
;
380 * Create an instance of an output formatter by its name
382 * @param string $format
384 * @return ApiFormatBase
386 public function createPrinterByName( $format ) {
387 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
388 if ( $printer === null ) {
389 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
396 * Execute api request. Any errors will be handled if the API was called by the remote client.
398 public function execute() {
399 if ( $this->mInternalMode
) {
400 $this->executeAction();
402 $this->executeActionWithErrorHandling();
407 * Execute an action, and in case of an error, erase whatever partial results
408 * have been accumulated, and replace it with an error message and a help screen.
410 protected function executeActionWithErrorHandling() {
411 // Verify the CORS header before executing the action
412 if ( !$this->handleCORS() ) {
413 // handleCORS() has sent a 403, abort
417 // Exit here if the request method was OPTIONS
418 // (assume there will be a followup GET or POST)
419 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
423 // In case an error occurs during data output,
424 // clear the output buffer and print just the error information
425 $obLevel = ob_get_level();
428 $t = microtime( true );
431 $this->executeAction();
432 $runTime = microtime( true ) - $t;
433 $this->logRequest( $runTime );
434 if ( $this->mModule
->isWriteMode() && $this->getRequest()->wasPosted() ) {
435 $this->getStats()->timing(
436 'api.' . $this->getModuleName() . '.executeTiming', 1000 * $runTime );
438 } catch ( Exception
$e ) {
439 $this->handleException( $e );
440 $this->logRequest( microtime( true ) - $t, $e );
444 // Commit DBs and send any related cookies and headers
445 MediaWiki
::preOutputCommit( $this->getContext() );
447 // Send cache headers after any code which might generate an error, to
448 // avoid sending public cache headers for errors.
449 $this->sendCacheHeaders( $isError );
451 // Executing the action might have already messed with the output
453 while ( ob_get_level() > $obLevel ) {
459 * Handle an exception as an API response
462 * @param Exception $e
464 protected function handleException( Exception
$e ) {
465 // Bug 63145: Rollback any open database transactions
466 if ( !( $e instanceof UsageException
) ) {
467 // UsageExceptions are intentional, so don't rollback if that's the case
469 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
470 } catch ( DBError
$e2 ) {
471 // Rollback threw an exception too. Log it, but don't interrupt
472 // our regularly scheduled exception handling.
473 MWExceptionHandler
::logException( $e2 );
477 // Allow extra cleanup and logging
478 Hooks
::run( 'ApiMain::onException', [ $this, $e ] );
481 if ( !( $e instanceof UsageException
) ) {
482 MWExceptionHandler
::logException( $e );
485 // Handle any kind of exception by outputting properly formatted error message.
486 // If this fails, an unhandled exception should be thrown so that global error
487 // handler will process and log it.
489 $errCode = $this->substituteResultWithError( $e );
491 // Error results should not be cached
492 $this->setCacheMode( 'private' );
494 $response = $this->getRequest()->response();
495 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
496 if ( $e->getCode() === 0 ) {
497 $response->header( $headerStr );
499 $response->header( $headerStr, true, $e->getCode() );
502 // Reset and print just the error message
505 // Printer may not be initialized if the extractRequestParams() fails for the main module
506 $this->createErrorPrinter();
509 $this->printResult( true );
510 } catch ( UsageException
$ex ) {
511 // The error printer itself is failing. Try suppressing its request
512 // parameters and redo.
514 'Error printer failed (will retry without params): ' . $ex->getMessage()
516 $this->mPrinter
= null;
517 $this->createErrorPrinter();
518 $this->mPrinter
->forceDefaultParams();
519 $this->printResult( true );
524 * Handle an exception from the ApiBeforeMain hook.
526 * This tries to print the exception as an API response, to be more
527 * friendly to clients. If it fails, it will rethrow the exception.
530 * @param Exception $e
533 public static function handleApiBeforeMainException( Exception
$e ) {
537 $main = new self( RequestContext
::getMain(), false );
538 $main->handleException( $e );
539 $main->logRequest( 0, $e );
540 } catch ( Exception
$e2 ) {
541 // Nope, even that didn't work. Punt.
545 // Reset cache headers
546 $main->sendCacheHeaders( true );
552 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
554 * If no origin parameter is present, nothing happens.
555 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
556 * is set and false is returned.
557 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
558 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
560 * http://www.w3.org/TR/cors/#resource-requests
561 * http://www.w3.org/TR/cors/#resource-preflight-requests
563 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
565 protected function handleCORS() {
566 $originParam = $this->getParameter( 'origin' ); // defaults to null
567 if ( $originParam === null ) {
568 // No origin parameter, nothing to do
572 $request = $this->getRequest();
573 $response = $request->response();
575 // Origin: header is a space-separated list of origins, check all of them
576 $originHeader = $request->getHeader( 'Origin' );
577 if ( $originHeader === false ) {
580 $originHeader = trim( $originHeader );
581 $origins = preg_split( '/\s+/', $originHeader );
584 if ( !in_array( $originParam, $origins ) ) {
585 // origin parameter set but incorrect
586 // Send a 403 response
587 $response->statusHeader( 403 );
588 $response->header( 'Cache-Control: no-cache' );
589 echo "'origin' parameter does not match Origin header\n";
594 $config = $this->getConfig();
595 $matchOrigin = count( $origins ) === 1 && self
::matchOrigin(
597 $config->get( 'CrossSiteAJAXdomains' ),
598 $config->get( 'CrossSiteAJAXdomainExceptions' )
601 if ( $matchOrigin ) {
602 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
603 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
605 // This is a CORS preflight request
606 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
607 // If method is not a case-sensitive match, do not set any additional headers and terminate.
610 // We allow the actual request to send the following headers
611 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
612 if ( $requestedHeaders !== false ) {
613 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
616 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
619 // We only allow the actual request to be GET or POST
620 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
623 $response->header( "Access-Control-Allow-Origin: $originHeader" );
624 $response->header( 'Access-Control-Allow-Credentials: true' );
625 // http://www.w3.org/TR/resource-timing/#timing-allow-origin
626 $response->header( "Timing-Allow-Origin: $originHeader" );
630 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag'
635 $this->getOutput()->addVaryHeader( 'Origin' );
640 * Attempt to match an Origin header against a set of rules and a set of exceptions
641 * @param string $value Origin header
642 * @param array $rules Set of wildcard rules
643 * @param array $exceptions Set of wildcard rules
644 * @return bool True if $value matches a rule in $rules and doesn't match
645 * any rules in $exceptions, false otherwise
647 protected static function matchOrigin( $value, $rules, $exceptions ) {
648 foreach ( $rules as $rule ) {
649 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
650 // Rule matches, check exceptions
651 foreach ( $exceptions as $exc ) {
652 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
665 * Attempt to validate the value of Access-Control-Request-Headers against a list
666 * of headers that we allow the follow up request to send.
668 * @param string $requestedHeaders Comma seperated list of HTTP headers
669 * @return bool True if all requested headers are in the list of allowed headers
671 protected static function matchRequestedHeaders( $requestedHeaders ) {
672 if ( trim( $requestedHeaders ) === '' ) {
675 $requestedHeaders = explode( ',', $requestedHeaders );
676 $allowedAuthorHeaders = array_flip( [
677 /* simple headers (see spec) */
682 /* non-authorable headers in XHR, which are however requested by some UAs */
686 /* MediaWiki whitelist */
689 foreach ( $requestedHeaders as $rHeader ) {
690 $rHeader = strtolower( trim( $rHeader ) );
691 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
692 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
700 * Helper function to convert wildcard string into a regex
704 * @param string $wildcard String with wildcards
705 * @return string Regular expression
707 protected static function wildcardToRegex( $wildcard ) {
708 $wildcard = preg_quote( $wildcard, '/' );
709 $wildcard = str_replace(
715 return "/^https?:\/\/$wildcard$/";
719 * Send caching headers
720 * @param bool $isError Whether an error response is being output
721 * @since 1.26 added $isError parameter
723 protected function sendCacheHeaders( $isError ) {
724 $response = $this->getRequest()->response();
725 $out = $this->getOutput();
727 $config = $this->getConfig();
729 if ( $config->get( 'VaryOnXFP' ) ) {
730 $out->addVaryHeader( 'X-Forwarded-Proto' );
733 if ( !$isError && $this->mModule
&&
734 ( $this->getRequest()->getMethod() === 'GET' ||
$this->getRequest()->getMethod() === 'HEAD' )
736 $etag = $this->mModule
->getConditionalRequestData( 'etag' );
737 if ( $etag !== null ) {
738 $response->header( "ETag: $etag" );
740 $lastMod = $this->mModule
->getConditionalRequestData( 'last-modified' );
741 if ( $lastMod !== null ) {
742 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $lastMod ) );
746 // The logic should be:
747 // $this->mCacheControl['max-age'] is set?
748 // Use it, the module knows better than our guess.
749 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
750 // Use 0 because we can guess caching is probably the wrong thing to do.
751 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
753 if ( isset( $this->mCacheControl
['max-age'] ) ) {
754 $maxage = $this->mCacheControl
['max-age'];
755 } elseif ( ( $this->mModule
&& !$this->mModule
->isWriteMode() ) ||
756 $this->mCacheMode
!== 'private'
758 $maxage = $this->getParameter( 'maxage' );
760 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
762 if ( $this->mCacheMode
== 'private' ) {
763 $response->header( "Cache-Control: $privateCache" );
767 $useKeyHeader = $config->get( 'UseKeyHeader' );
768 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
769 $out->addVaryHeader( 'Cookie' );
770 $response->header( $out->getVaryHeader() );
771 if ( $useKeyHeader ) {
772 $response->header( $out->getKeyHeader() );
773 if ( $out->haveCacheVaryCookies() ) {
774 // Logged in, mark this request private
775 $response->header( "Cache-Control: $privateCache" );
778 // Logged out, send normal public headers below
779 } elseif ( MediaWiki\Session\SessionManager
::getGlobalSession()->isPersistent() ) {
780 // Logged in or otherwise has session (e.g. anonymous users who have edited)
781 // Mark request private
782 $response->header( "Cache-Control: $privateCache" );
785 } // else no Key and anonymous, send public headers below
788 // Send public headers
789 $response->header( $out->getVaryHeader() );
790 if ( $useKeyHeader ) {
791 $response->header( $out->getKeyHeader() );
794 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
795 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
796 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
798 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
799 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
802 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
803 // Public cache not requested
804 // Sending a Vary header in this case is harmless, and protects us
805 // against conditional calls of setCacheMaxAge().
806 $response->header( "Cache-Control: $privateCache" );
811 $this->mCacheControl
['public'] = true;
813 // Send an Expires header
814 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
815 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
816 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
818 // Construct the Cache-Control header
821 foreach ( $this->mCacheControl
as $name => $value ) {
822 if ( is_bool( $value ) ) {
824 $ccHeader .= $separator . $name;
828 $ccHeader .= $separator . "$name=$value";
833 $response->header( "Cache-Control: $ccHeader" );
837 * Create the printer for error output
839 private function createErrorPrinter() {
840 if ( !isset( $this->mPrinter
) ) {
841 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
842 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
843 $value = self
::API_DEFAULT_FORMAT
;
845 $this->mPrinter
= $this->createPrinterByName( $value );
848 // Printer may not be able to handle errors. This is particularly
849 // likely if the module returns something for getCustomPrinter().
850 if ( !$this->mPrinter
->canPrintErrors() ) {
851 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
856 * Create an error message for the given exception.
858 * If the exception is a UsageException then
859 * UsageException::getMessageArray() will be called to create the message.
861 * @param Exception $e
862 * @return array ['code' => 'some string', 'info' => 'some other string']
865 protected function errorMessageFromException( $e ) {
866 if ( $e instanceof UsageException
) {
867 // User entered incorrect parameters - generate error response
868 $errMessage = $e->getMessageArray();
870 $config = $this->getConfig();
871 // Something is seriously wrong
872 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
873 $info = 'Database query error';
875 $info = "Exception Caught: {$e->getMessage()}";
879 'code' => 'internal_api_error_' . get_class( $e ),
880 'info' => '[' . WebRequest
::getRequestId() . '] ' . $info,
887 * Replace the result data with the information about an exception.
888 * Returns the error code
889 * @param Exception $e
892 protected function substituteResultWithError( $e ) {
893 $result = $this->getResult();
894 $config = $this->getConfig();
896 $errMessage = $this->errorMessageFromException( $e );
897 if ( $e instanceof UsageException
) {
898 // User entered incorrect parameters - generate error response
899 $link = wfExpandUrl( wfScript( 'api' ) );
900 ApiResult
::setContentValue( $errMessage, 'docref', "See $link for API usage" );
902 // Something is seriously wrong
903 if ( $config->get( 'ShowExceptionDetails' ) ) {
904 ApiResult
::setContentValue(
907 MWExceptionHandler
::getRedactedTraceAsString( $e )
912 // Remember all the warnings to re-add them later
913 $warnings = $result->getResultData( [ 'warnings' ] );
917 $requestid = $this->getParameter( 'requestid' );
918 if ( !is_null( $requestid ) ) {
919 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
921 if ( $config->get( 'ShowHostnames' ) ) {
922 // servedby is especially useful when debugging errors
923 $result->addValue( null, 'servedby', wfHostname(), ApiResult
::NO_SIZE_CHECK
);
925 if ( $warnings !== null ) {
926 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
929 $result->addValue( null, 'error', $errMessage, ApiResult
::NO_SIZE_CHECK
);
931 return $errMessage['code'];
935 * Set up for the execution.
938 protected function setupExecuteAction() {
939 // First add the id to the top element
940 $result = $this->getResult();
941 $requestid = $this->getParameter( 'requestid' );
942 if ( !is_null( $requestid ) ) {
943 $result->addValue( null, 'requestid', $requestid );
946 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
947 $servedby = $this->getParameter( 'servedby' );
949 $result->addValue( null, 'servedby', wfHostname() );
953 if ( $this->getParameter( 'curtimestamp' ) ) {
954 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
955 ApiResult
::NO_SIZE_CHECK
);
958 $params = $this->extractRequestParams();
960 $this->mAction
= $params['action'];
962 if ( !is_string( $this->mAction
) ) {
963 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
970 * Set up the module for response
971 * @return ApiBase The module that will handle this action
972 * @throws MWException
973 * @throws UsageException
975 protected function setupModule() {
976 // Instantiate the module requested by the user
977 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
978 if ( $module === null ) {
979 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
981 $moduleParams = $module->extractRequestParams();
983 // Check token, if necessary
984 if ( $module->needsToken() === true ) {
985 throw new MWException(
986 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
987 'See documentation for ApiBase::needsToken for details.'
990 if ( $module->needsToken() ) {
991 if ( !$module->mustBePosted() ) {
992 throw new MWException(
993 "Module '{$module->getModuleName()}' must require POST to use tokens."
997 if ( !isset( $moduleParams['token'] ) ) {
998 $this->dieUsageMsg( [ 'missingparam', 'token' ] );
1001 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
1003 $module->encodeParamName( 'token' ),
1004 $this->getRequest()->getQueryValues()
1008 "The '{$module->encodeParamName( 'token' )}' parameter was " .
1009 'found in the query string, but must be in the POST body',
1014 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1015 $this->dieUsageMsg( 'sessionfailure' );
1023 * Check the max lag if necessary
1024 * @param ApiBase $module Api module being used
1025 * @param array $params Array an array containing the request parameters.
1026 * @return bool True on success, false should exit immediately
1028 protected function checkMaxLag( $module, $params ) {
1029 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1030 $maxLag = $params['maxlag'];
1031 list( $host, $lag ) = wfGetLB()->getMaxLag();
1032 if ( $lag > $maxLag ) {
1033 $response = $this->getRequest()->response();
1035 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1036 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
1038 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1039 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
1042 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
1050 * Check selected RFC 7232 precondition headers
1052 * RFC 7232 envisions a particular model where you send your request to "a
1053 * resource", and for write requests that you can read "the resource" by
1054 * changing the method to GET. When the API receives a GET request, it
1055 * works out even though "the resource" from RFC 7232's perspective might
1056 * be many resources from MediaWiki's perspective. But it totally fails for
1057 * a POST, since what HTTP sees as "the resource" is probably just
1058 * "/api.php" with all the interesting bits in the body.
1060 * Therefore, we only support RFC 7232 precondition headers for GET (and
1061 * HEAD). That means we don't need to bother with If-Match and
1062 * If-Unmodified-Since since they only apply to modification requests.
1064 * And since we don't support Range, If-Range is ignored too.
1067 * @param ApiBase $module Api module being used
1068 * @return bool True on success, false should exit immediately
1070 protected function checkConditionalRequestHeaders( $module ) {
1071 if ( $this->mInternalMode
) {
1072 // No headers to check in internal mode
1076 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1077 // Don't check POSTs
1083 $ifNoneMatch = array_diff(
1084 $this->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
) ?
: [],
1087 if ( $ifNoneMatch ) {
1088 if ( $ifNoneMatch === [ '*' ] ) {
1089 // API responses always "exist"
1092 $etag = $module->getConditionalRequestData( 'etag' );
1095 if ( $ifNoneMatch && $etag !== null ) {
1096 $test = substr( $etag, 0, 2 ) === 'W/' ?
substr( $etag, 2 ) : $etag;
1097 $match = array_map( function ( $s ) {
1098 return substr( $s, 0, 2 ) === 'W/' ?
substr( $s, 2 ) : $s;
1100 $return304 = in_array( $test, $match, true );
1102 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1104 // Some old browsers sends sizes after the date, like this:
1105 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1107 $i = strpos( $value, ';' );
1108 if ( $i !== false ) {
1109 $value = trim( substr( $value, 0, $i ) );
1112 if ( $value !== '' ) {
1114 $ts = new MWTimestamp( $value );
1116 // RFC 7231 IMF-fixdate
1117 $ts->getTimestamp( TS_RFC2822
) === $value ||
1119 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1120 // asctime (with and without space-padded day)
1121 $ts->format( 'D M j H:i:s Y' ) === $value ||
1122 $ts->format( 'D M j H:i:s Y' ) === $value
1124 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1125 if ( $lastMod !== null ) {
1126 // Mix in some MediaWiki modification times
1129 'user' => $this->getUser()->getTouched(),
1130 'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1132 if ( $this->getConfig()->get( 'UseSquid' ) ) {
1133 // T46570: the core page itself may not change, but resources might
1134 $modifiedTimes['sepoch'] = wfTimestamp(
1135 TS_MW
, time() - $this->getConfig()->get( 'SquidMaxage' )
1138 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1139 $lastMod = max( $modifiedTimes );
1140 $return304 = wfTimestamp( TS_MW
, $lastMod ) <= $ts->getTimestamp( TS_MW
);
1143 } catch ( TimestampException
$e ) {
1144 // Invalid timestamp, ignore it
1150 $this->getRequest()->response()->statusHeader( 304 );
1152 // Avoid outputting the compressed representation of a zero-length body
1153 MediaWiki\
suppressWarnings();
1154 ini_set( 'zlib.output_compression', 0 );
1155 MediaWiki\restoreWarnings
();
1156 wfClearOutputBuffers();
1165 * Check for sufficient permissions to execute
1166 * @param ApiBase $module An Api module
1168 protected function checkExecutePermissions( $module ) {
1169 $user = $this->getUser();
1170 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
1171 !$user->isAllowed( 'read' )
1173 $this->dieUsageMsg( 'readrequired' );
1176 if ( $module->isWriteMode() ) {
1177 if ( !$this->mEnableWrite
) {
1178 $this->dieUsageMsg( 'writedisabled' );
1179 } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1180 $this->dieUsageMsg( 'writerequired' );
1181 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1183 'Promise-Non-Write-API-Action HTTP header cannot be sent to write API modules',
1184 'promised-nonwrite-api'
1188 $this->checkReadOnly( $module );
1191 // Allow extensions to stop execution for arbitrary reasons.
1193 if ( !Hooks
::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1194 $this->dieUsageMsg( $message );
1199 * Check if the DB is read-only for this user
1200 * @param ApiBase $module An Api module
1202 protected function checkReadOnly( $module ) {
1203 if ( wfReadOnly() ) {
1204 $this->dieReadOnly();
1207 if ( $module->isWriteMode()
1208 && in_array( 'bot', $this->getUser()->getGroups() )
1209 && wfGetLB()->getServerCount() > 1
1211 $this->checkBotReadOnly();
1216 * Check whether we are readonly for bots
1218 private function checkBotReadOnly() {
1219 // Figure out how many servers have passed the lag threshold
1221 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1222 $laggedServers = [];
1223 $loadBalancer = wfGetLB();
1224 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1225 if ( $lag > $lagLimit ) {
1227 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1231 // If a majority of slaves are too lagged then disallow writes
1232 $slaveCount = wfGetLB()->getServerCount() - 1;
1233 if ( $numLagged >= ceil( $slaveCount / 2 ) ) {
1234 $laggedServers = implode( ', ', $laggedServers );
1237 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1240 $parsed = $this->parseMsg( [ 'readonlytext' ] );
1246 [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1252 * Check asserts of the user's rights
1253 * @param array $params
1255 protected function checkAsserts( $params ) {
1256 if ( isset( $params['assert'] ) ) {
1257 $user = $this->getUser();
1258 switch ( $params['assert'] ) {
1260 if ( $user->isAnon() ) {
1261 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
1265 if ( !$user->isAllowed( 'bot' ) ) {
1266 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1274 * Check POST for external response and setup result printer
1275 * @param ApiBase $module An Api module
1276 * @param array $params An array with the request parameters
1278 protected function setupExternalResponse( $module, $params ) {
1279 $request = $this->getRequest();
1280 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1281 // Module requires POST. GET request might still be allowed
1282 // if $wgDebugApi is true, otherwise fail.
1283 $this->dieUsageMsgOrDebug( [ 'mustbeposted', $this->mAction
] );
1286 // See if custom printer is used
1287 $this->mPrinter
= $module->getCustomPrinter();
1288 if ( is_null( $this->mPrinter
) ) {
1289 // Create an appropriate printer
1290 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1293 if ( $request->getProtocol() === 'http' && (
1294 $request->getSession()->shouldForceHTTPS() ||
1295 ( $this->getUser()->isLoggedIn() &&
1296 $this->getUser()->requiresHTTPS() )
1298 $this->logFeatureUsage( 'https-expected' );
1299 $this->setWarning( 'HTTP used when HTTPS was expected' );
1304 * Execute the actual module, without any error handling
1306 protected function executeAction() {
1307 $params = $this->setupExecuteAction();
1308 $module = $this->setupModule();
1309 $this->mModule
= $module;
1311 if ( !$this->mInternalMode
) {
1312 $this->setRequestExpectations( $module );
1315 $this->checkExecutePermissions( $module );
1317 if ( !$this->checkMaxLag( $module, $params ) ) {
1321 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1325 if ( !$this->mInternalMode
) {
1326 $this->setupExternalResponse( $module, $params );
1329 $this->checkAsserts( $params );
1333 Hooks
::run( 'APIAfterExecute', [ &$module ] );
1335 $this->reportUnusedParams();
1337 if ( !$this->mInternalMode
) {
1338 // append Debug information
1339 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1341 // Print result data
1342 $this->printResult( false );
1347 * Set database connection, query, and write expectations given this module request
1348 * @param ApiBase $module
1350 protected function setRequestExpectations( ApiBase
$module ) {
1351 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1352 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1353 if ( $this->getRequest()->wasPosted() ) {
1354 if ( $module->isWriteMode() ) {
1355 $trxProfiler->setExpectations( $limits['POST'], __METHOD__
);
1357 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__
);
1358 $this->getRequest()->markAsSafeRequest();
1361 $trxProfiler->setExpectations( $limits['GET'], __METHOD__
);
1366 * Log the preceding request
1367 * @param float $time Time in seconds
1368 * @param Exception $e Exception caught while processing the request
1370 protected function logRequest( $time, $e = null ) {
1371 $request = $this->getRequest();
1374 'ip' => $request->getIP(),
1375 'userAgent' => $this->getUserAgent(),
1376 'wiki' => wfWikiID(),
1377 'timeSpentBackend' => (int) round( $time * 1000 ),
1378 'hadError' => $e !== null,
1384 $logCtx['errorCodes'][] = $this->errorMessageFromException( $e )['code'];
1387 // Construct space separated message for 'api' log channel
1388 $msg = "API {$request->getMethod()} " .
1389 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1390 " {$logCtx['ip']} " .
1391 "T={$logCtx['timeSpentBackend']}ms";
1393 foreach ( $this->getParamsUsed() as $name ) {
1394 $value = $request->getVal( $name );
1395 if ( $value === null ) {
1399 if ( strlen( $value ) > 256 ) {
1400 $value = substr( $value, 0, 256 );
1401 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1403 $encValue = $this->encodeRequestLogValue( $value );
1406 $logCtx['params'][$name] = $value;
1407 $msg .= " {$name}={$encValue}";
1410 wfDebugLog( 'api', $msg, 'private' );
1411 // ApiAction channel is for structured data consumers
1412 wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1416 * Encode a value in a format suitable for a space-separated log line.
1420 protected function encodeRequestLogValue( $s ) {
1423 $chars = ';@$!*(),/:';
1424 $numChars = strlen( $chars );
1425 for ( $i = 0; $i < $numChars; $i++
) {
1426 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1430 return strtr( rawurlencode( $s ), $table );
1434 * Get the request parameters used in the course of the preceding execute() request
1437 protected function getParamsUsed() {
1438 return array_keys( $this->mParamsUsed
);
1442 * Get a request value, and register the fact that it was used, for logging.
1443 * @param string $name
1444 * @param mixed $default
1447 public function getVal( $name, $default = null ) {
1448 $this->mParamsUsed
[$name] = true;
1450 $ret = $this->getRequest()->getVal( $name );
1451 if ( $ret === null ) {
1452 if ( $this->getRequest()->getArray( $name ) !== null ) {
1453 // See bug 10262 for why we don't just implode( '|', ... ) the
1456 "Parameter '$name' uses unsupported PHP array syntax"
1465 * Get a boolean request value, and register the fact that the parameter
1466 * was used, for logging.
1467 * @param string $name
1470 public function getCheck( $name ) {
1471 return $this->getVal( $name, null ) !== null;
1475 * Get a request upload, and register the fact that it was used, for logging.
1478 * @param string $name Parameter name
1479 * @return WebRequestUpload
1481 public function getUpload( $name ) {
1482 $this->mParamsUsed
[$name] = true;
1484 return $this->getRequest()->getUpload( $name );
1488 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1489 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1491 protected function reportUnusedParams() {
1492 $paramsUsed = $this->getParamsUsed();
1493 $allParams = $this->getRequest()->getValueNames();
1495 if ( !$this->mInternalMode
) {
1496 // Printer has not yet executed; don't warn that its parameters are unused
1497 $printerParams = array_map(
1498 [ $this->mPrinter
, 'encodeParamName' ],
1499 array_keys( $this->mPrinter
->getFinalParams() ?
: [] )
1501 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1503 $unusedParams = array_diff( $allParams, $paramsUsed );
1506 if ( count( $unusedParams ) ) {
1507 $s = count( $unusedParams ) > 1 ?
's' : '';
1508 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1513 * Print results using the current printer
1515 * @param bool $isError
1517 protected function printResult( $isError ) {
1518 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1519 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1522 $printer = $this->mPrinter
;
1523 $printer->initPrinter( false );
1524 $printer->execute();
1525 $printer->closePrinter();
1531 public function isReadMode() {
1536 * See ApiBase for description.
1540 public function getAllowedParams() {
1543 ApiBase
::PARAM_DFLT
=> 'help',
1544 ApiBase
::PARAM_TYPE
=> 'submodule',
1547 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1548 ApiBase
::PARAM_TYPE
=> 'submodule',
1551 ApiBase
::PARAM_TYPE
=> 'integer'
1554 ApiBase
::PARAM_TYPE
=> 'integer',
1555 ApiBase
::PARAM_DFLT
=> 0
1558 ApiBase
::PARAM_TYPE
=> 'integer',
1559 ApiBase
::PARAM_DFLT
=> 0
1562 ApiBase
::PARAM_TYPE
=> [ 'user', 'bot' ]
1564 'requestid' => null,
1565 'servedby' => false,
1566 'curtimestamp' => false,
1569 ApiBase
::PARAM_DFLT
=> 'user',
1574 /** @see ApiBase::getExamplesMessages() */
1575 protected function getExamplesMessages() {
1578 => 'apihelp-help-example-main',
1579 'action=help&recursivesubmodules=1'
1580 => 'apihelp-help-example-recursive',
1584 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1585 // Wish PHP had an "array_insert_before". Instead, we have to manually
1586 // reindex the array to get 'permissions' in the right place.
1589 foreach ( $oldHelp as $k => $v ) {
1590 if ( $k === 'submodules' ) {
1591 $help['permissions'] = '';
1595 $help['datatypes'] = '';
1596 $help['credits'] = '';
1598 // Fill 'permissions'
1599 $help['permissions'] .= Html
::openElement( 'div',
1600 [ 'class' => 'apihelp-block apihelp-permissions' ] );
1601 $m = $this->msg( 'api-help-permissions' );
1602 if ( !$m->isDisabled() ) {
1603 $help['permissions'] .= Html
::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1604 $m->numParams( count( self
::$mRights ) )->parse()
1607 $help['permissions'] .= Html
::openElement( 'dl' );
1608 foreach ( self
::$mRights as $right => $rightMsg ) {
1609 $help['permissions'] .= Html
::element( 'dt', null, $right );
1611 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1612 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1614 $groups = array_map( function ( $group ) {
1615 return $group == '*' ?
'all' : $group;
1616 }, User
::getGroupsWithPermission( $right ) );
1618 $help['permissions'] .= Html
::rawElement( 'dd', null,
1619 $this->msg( 'api-help-permissions-granted-to' )
1620 ->numParams( count( $groups ) )
1621 ->params( $this->getLanguage()->commaList( $groups ) )
1625 $help['permissions'] .= Html
::closeElement( 'dl' );
1626 $help['permissions'] .= Html
::closeElement( 'div' );
1628 // Fill 'datatypes' and 'credits', if applicable
1629 if ( empty( $options['nolead'] ) ) {
1630 $level = $options['headerlevel'];
1631 $tocnumber = &$options['tocnumber'];
1633 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1634 $help['datatypes'] .= Html
::rawElement( 'h' . min( 6, $level ),
1635 [ 'id' => 'main/datatypes', 'class' => 'apihelp-header' ],
1636 Html
::element( 'span', [ 'id' => Sanitizer
::escapeId( 'main/datatypes' ) ] ) .
1639 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1640 if ( !isset( $tocData['main/datatypes'] ) ) {
1641 $tocnumber[$level]++
;
1642 $tocData['main/datatypes'] = [
1643 'toclevel' => count( $tocnumber ),
1645 'anchor' => 'main/datatypes',
1647 'number' => implode( '.', $tocnumber ),
1652 $header = $this->msg( 'api-credits-header' )->parse();
1653 $help['credits'] .= Html
::rawElement( 'h' . min( 6, $level ),
1654 [ 'id' => 'main/credits', 'class' => 'apihelp-header' ],
1655 Html
::element( 'span', [ 'id' => Sanitizer
::escapeId( 'main/credits' ) ] ) .
1658 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1659 if ( !isset( $tocData['main/credits'] ) ) {
1660 $tocnumber[$level]++
;
1661 $tocData['main/credits'] = [
1662 'toclevel' => count( $tocnumber ),
1664 'anchor' => 'main/credits',
1666 'number' => implode( '.', $tocnumber ),
1673 private $mCanApiHighLimits = null;
1676 * Check whether the current user is allowed to use high limits
1679 public function canApiHighLimits() {
1680 if ( !isset( $this->mCanApiHighLimits
) ) {
1681 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1684 return $this->mCanApiHighLimits
;
1688 * Overrides to return this instance's module manager.
1689 * @return ApiModuleManager
1691 public function getModuleManager() {
1692 return $this->mModuleMgr
;
1696 * Fetches the user agent used for this request
1698 * The value will be the combination of the 'Api-User-Agent' header (if
1699 * any) and the standard User-Agent header (if any).
1703 public function getUserAgent() {
1705 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1706 $this->getRequest()->getHeader( 'User-agent' )
1710 /************************************************************************//**
1716 * Sets whether the pretty-printer should format *bold* and $italics$
1718 * @deprecated since 1.25
1721 public function setHelp( $help = true ) {
1722 wfDeprecated( __METHOD__
, '1.25' );
1723 $this->mPrinter
->setHelp( $help );
1727 * Override the parent to generate help messages for all available modules.
1729 * @deprecated since 1.25
1732 public function makeHelpMsg() {
1733 wfDeprecated( __METHOD__
, '1.25' );
1736 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1738 return ObjectCache
::getMainWANInstance()->getWithSetCallback(
1741 $this->getModuleName(),
1742 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) )
1744 $cacheHelpTimeout > 0 ?
$cacheHelpTimeout : WANObjectCache
::TTL_UNCACHEABLE
,
1745 [ $this, 'reallyMakeHelpMsg' ]
1750 * @deprecated since 1.25
1751 * @return mixed|string
1753 public function reallyMakeHelpMsg() {
1754 wfDeprecated( __METHOD__
, '1.25' );
1757 // Use parent to make default message for the main module
1758 $msg = parent
::makeHelpMsg();
1760 $asterisks = str_repeat( '*** ', 14 );
1761 $msg .= "\n\n$asterisks Modules $asterisks\n\n";
1763 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1764 $module = $this->mModuleMgr
->getModule( $name );
1765 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1767 $msg2 = $module->makeHelpMsg();
1768 if ( $msg2 !== false ) {
1774 $msg .= "\n$asterisks Permissions $asterisks\n\n";
1775 foreach ( self
::$mRights as $right => $rightMsg ) {
1776 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1777 ->useDatabase( false )
1778 ->inLanguage( 'en' )
1780 $groups = User
::getGroupsWithPermission( $right );
1781 $msg .= '* ' . $right . " *\n $rightsMsg" .
1782 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1785 $msg .= "\n$asterisks Formats $asterisks\n\n";
1786 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1787 $module = $this->mModuleMgr
->getModule( $name );
1788 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1789 $msg2 = $module->makeHelpMsg();
1790 if ( $msg2 !== false ) {
1796 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1797 $credits = str_replace( "\n", "\n ", $credits );
1798 $msg .= "\n*** Credits: ***\n $credits\n";
1804 * @deprecated since 1.25
1805 * @param ApiBase $module
1806 * @param string $paramName What type of request is this? e.g. action,
1807 * query, list, prop, meta, format
1810 public static function makeHelpMsgHeader( $module, $paramName ) {
1811 wfDeprecated( __METHOD__
, '1.25' );
1812 $modulePrefix = $module->getModulePrefix();
1813 if ( strval( $modulePrefix ) !== '' ) {
1814 $modulePrefix = "($modulePrefix) ";
1817 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1825 * This exception will be thrown when dieUsage is called to stop module execution.
1829 class UsageException
extends MWException
{
1836 private $mExtraData;
1839 * @param string $message
1840 * @param string $codestr
1842 * @param array|null $extradata
1844 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1845 parent
::__construct( $message, $code );
1846 $this->mCodestr
= $codestr;
1847 $this->mExtraData
= $extradata;
1853 public function getCodeString() {
1854 return $this->mCodestr
;
1860 public function getMessageArray() {
1862 'code' => $this->mCodestr
,
1863 'info' => $this->getMessage()
1865 if ( is_array( $this->mExtraData
) ) {
1866 $result = array_merge( $result, $this->mExtraData
);
1875 public function __toString() {
1876 return "{$this->getCodeString()}: {$this->getMessage()}";
1881 * For really cool vim folding this needs to be at the end:
1882 * vim: foldmarker=@{,@} foldmethod=marker