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',
74 'cspreport' => 'ApiCSPReport',
77 'purge' => 'ApiPurge',
78 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
79 'rollback' => 'ApiRollback',
80 'delete' => 'ApiDelete',
81 'undelete' => 'ApiUndelete',
82 'protect' => 'ApiProtect',
83 'block' => 'ApiBlock',
84 'unblock' => 'ApiUnblock',
86 'edit' => 'ApiEditPage',
87 'upload' => 'ApiUpload',
88 'filerevert' => 'ApiFileRevert',
89 'emailuser' => 'ApiEmailUser',
90 'watch' => 'ApiWatch',
91 'patrol' => 'ApiPatrol',
92 'import' => 'ApiImport',
93 'clearhasmsg' => 'ApiClearHasMsg',
94 'userrights' => 'ApiUserrights',
95 'options' => 'ApiOptions',
96 'imagerotate' => 'ApiImageRotate',
97 'revisiondelete' => 'ApiRevisionDelete',
98 'managetags' => 'ApiManageTags',
100 'mergehistory' => 'ApiMergeHistory',
104 * List of available formats: format name => format class
106 private static $Formats = [
107 'json' => 'ApiFormatJson',
108 'jsonfm' => 'ApiFormatJson',
109 'php' => 'ApiFormatPhp',
110 'phpfm' => 'ApiFormatPhp',
111 'xml' => 'ApiFormatXml',
112 'xmlfm' => 'ApiFormatXml',
113 'rawfm' => 'ApiFormatJson',
114 'none' => 'ApiFormatNone',
117 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
119 * List of user roles that are specifically relevant to the API.
120 * array( 'right' => array ( 'msg' => 'Some message with a $1',
121 * 'params' => array ( $someVarToSubst ) ),
124 private static $mRights = [
126 'msg' => 'right-writeapi',
130 'msg' => 'api-help-right-apihighlimits',
131 'params' => [ ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
]
134 // @codingStandardsIgnoreEnd
141 private $mModuleMgr, $mResult, $mErrorFormatter;
142 /** @var ApiContinuationManager|null */
143 private $mContinuationManager;
145 private $mEnableWrite;
146 private $mInternalMode, $mSquidMaxage;
150 private $mCacheMode = 'private';
151 private $mCacheControl = [];
152 private $mParamsUsed = [];
154 /** @var bool|null Cached return value from self::lacksSameOriginSecurity() */
155 private $lacksSameOriginSecurity = null;
158 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
160 * @param IContextSource|WebRequest $context If this is an instance of
161 * FauxRequest, errors are thrown and no printing occurs
162 * @param bool $enableWrite Should be set to true if the api may modify data
164 public function __construct( $context = null, $enableWrite = false ) {
165 if ( $context === null ) {
166 $context = RequestContext
::getMain();
167 } elseif ( $context instanceof WebRequest
) {
170 $context = RequestContext
::getMain();
172 // We set a derivative context so we can change stuff later
173 $this->setContext( new DerivativeContext( $context ) );
175 if ( isset( $request ) ) {
176 $this->getContext()->setRequest( $request );
179 $this->mInternalMode
= ( $this->getRequest() instanceof FauxRequest
);
181 // Special handling for the main module: $parent === $this
182 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
184 if ( !$this->mInternalMode
) {
185 // Impose module restrictions.
186 // If the current user cannot read,
187 // Remove all modules other than login
190 if ( $this->lacksSameOriginSecurity() ) {
191 // If we're in a mode that breaks the same-origin policy, strip
192 // user credentials for security.
193 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
194 $wgUser = new User();
195 $this->getContext()->setUser( $wgUser );
199 $uselang = $this->getParameter( 'uselang' );
200 if ( $uselang === 'user' ) {
201 // Assume the parent context is going to return the user language
202 // for uselang=user (see T85635).
204 if ( $uselang === 'content' ) {
206 $uselang = $wgContLang->getCode();
208 $code = RequestContext
::sanitizeLangCode( $uselang );
209 $this->getContext()->setLanguage( $code );
210 if ( !$this->mInternalMode
) {
212 $wgLang = $this->getContext()->getLanguage();
213 RequestContext
::getMain()->setLanguage( $wgLang );
217 $config = $this->getConfig();
218 $this->mModuleMgr
= new ApiModuleManager( $this );
219 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
220 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
221 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
222 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
224 Hooks
::run( 'ApiMain::moduleManager', [ $this->mModuleMgr
] );
226 $this->mResult
= new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
227 $this->mErrorFormatter
= new ApiErrorFormatter_BackCompat( $this->mResult
);
228 $this->mResult
->setErrorFormatter( $this->mErrorFormatter
);
229 $this->mResult
->setMainForContinuation( $this );
230 $this->mContinuationManager
= null;
231 $this->mEnableWrite
= $enableWrite;
233 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
234 $this->mCommit
= false;
238 * Return true if the API was started by other PHP code using FauxRequest
241 public function isInternalMode() {
242 return $this->mInternalMode
;
246 * Get the ApiResult object associated with current request
250 public function getResult() {
251 return $this->mResult
;
255 * Get the security flag for the current request
258 public function lacksSameOriginSecurity() {
259 if ( $this->lacksSameOriginSecurity
!== null ) {
260 return $this->lacksSameOriginSecurity
;
263 $request = $this->getRequest();
266 if ( $request->getVal( 'callback' ) !== null ) {
267 $this->lacksSameOriginSecurity
= true;
271 // Header to be used from XMLHTTPRequest when the request might
272 // otherwise be used for XSS.
273 if ( $request->getHeader( 'Treat-as-Untrusted' ) !== false ) {
274 $this->lacksSameOriginSecurity
= true;
278 // Allow extensions to override.
279 $this->lacksSameOriginSecurity
= !Hooks
::run( 'RequestHasSameOriginSecurity', [ $request ] );
280 return $this->lacksSameOriginSecurity
;
284 * Get the ApiErrorFormatter object associated with current request
285 * @return ApiErrorFormatter
287 public function getErrorFormatter() {
288 return $this->mErrorFormatter
;
292 * Get the continuation manager
293 * @return ApiContinuationManager|null
295 public function getContinuationManager() {
296 return $this->mContinuationManager
;
300 * Set the continuation manager
301 * @param ApiContinuationManager|null
303 public function setContinuationManager( $manager ) {
304 if ( $manager !== null ) {
305 if ( !$manager instanceof ApiContinuationManager
) {
306 throw new InvalidArgumentException( __METHOD__
. ': Was passed ' .
307 is_object( $manager ) ?
get_class( $manager ) : gettype( $manager )
310 if ( $this->mContinuationManager
!== null ) {
311 throw new UnexpectedValueException(
312 __METHOD__
. ': tried to set manager from ' . $manager->getSource() .
313 ' when a manager is already set from ' . $this->mContinuationManager
->getSource()
317 $this->mContinuationManager
= $manager;
321 * Get the API module object. Only works after executeAction()
325 public function getModule() {
326 return $this->mModule
;
330 * Get the result formatter object. Only works after setupExecuteAction()
332 * @return ApiFormatBase
334 public function getPrinter() {
335 return $this->mPrinter
;
339 * Set how long the response should be cached.
343 public function setCacheMaxAge( $maxage ) {
344 $this->setCacheControl( [
345 'max-age' => $maxage,
346 's-maxage' => $maxage
351 * Set the type of caching headers which will be sent.
353 * @param string $mode One of:
354 * - 'public': Cache this object in public caches, if the maxage or smaxage
355 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
356 * not provided by any of these means, the object will be private.
357 * - 'private': Cache this object only in private client-side caches.
358 * - 'anon-public-user-private': Make this object cacheable for logged-out
359 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
360 * set consistently for a given URL, it cannot be set differently depending on
361 * things like the contents of the database, or whether the user is logged in.
363 * If the wiki does not allow anonymous users to read it, the mode set here
364 * will be ignored, and private caching headers will always be sent. In other words,
365 * the "public" mode is equivalent to saying that the data sent is as public as a page
368 * For user-dependent data, the private mode should generally be used. The
369 * anon-public-user-private mode should only be used where there is a particularly
370 * good performance reason for caching the anonymous response, but where the
371 * response to logged-in users may differ, or may contain private data.
373 * If this function is never called, then the default will be the private mode.
375 public function setCacheMode( $mode ) {
376 if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) {
377 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
379 // Ignore for forwards-compatibility
383 if ( !User
::isEveryoneAllowed( 'read' ) ) {
384 // Private wiki, only private headers
385 if ( $mode !== 'private' ) {
386 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
392 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
393 // User language is used for i18n, so we don't want to publicly
394 // cache. Anons are ok, because if they have non-default language
395 // then there's an appropriate Vary header set by whatever set
396 // their non-default language.
397 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
398 "'anon-public-user-private' due to uselang=user\n" );
399 $mode = 'anon-public-user-private';
402 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
403 $this->mCacheMode
= $mode;
407 * Set directives (key/value pairs) for the Cache-Control header.
408 * Boolean values will be formatted as such, by including or omitting
409 * without an equals sign.
411 * Cache control values set here will only be used if the cache mode is not
412 * private, see setCacheMode().
414 * @param array $directives
416 public function setCacheControl( $directives ) {
417 $this->mCacheControl
= $directives +
$this->mCacheControl
;
421 * Create an instance of an output formatter by its name
423 * @param string $format
425 * @return ApiFormatBase
427 public function createPrinterByName( $format ) {
428 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
429 if ( $printer === null ) {
430 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
437 * Execute api request. Any errors will be handled if the API was called by the remote client.
439 public function execute() {
440 if ( $this->mInternalMode
) {
441 $this->executeAction();
443 $this->executeActionWithErrorHandling();
448 * Execute an action, and in case of an error, erase whatever partial results
449 * have been accumulated, and replace it with an error message and a help screen.
451 protected function executeActionWithErrorHandling() {
452 // Verify the CORS header before executing the action
453 if ( !$this->handleCORS() ) {
454 // handleCORS() has sent a 403, abort
458 // Exit here if the request method was OPTIONS
459 // (assume there will be a followup GET or POST)
460 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
464 // In case an error occurs during data output,
465 // clear the output buffer and print just the error information
466 $obLevel = ob_get_level();
469 $t = microtime( true );
472 $this->executeAction();
473 $runTime = microtime( true ) - $t;
474 $this->logRequest( $runTime );
475 if ( $this->mModule
->isWriteMode() && $this->getRequest()->wasPosted() ) {
476 $this->getStats()->timing(
477 'api.' . $this->mModule
->getModuleName() . '.executeTiming', 1000 * $runTime
480 } catch ( Exception
$e ) {
481 $this->handleException( $e );
482 $this->logRequest( microtime( true ) - $t, $e );
486 // Commit DBs and send any related cookies and headers
487 MediaWiki
::preOutputCommit( $this->getContext() );
489 // Send cache headers after any code which might generate an error, to
490 // avoid sending public cache headers for errors.
491 $this->sendCacheHeaders( $isError );
493 // Executing the action might have already messed with the output
495 while ( ob_get_level() > $obLevel ) {
501 * Handle an exception as an API response
504 * @param Exception $e
506 protected function handleException( Exception
$e ) {
507 // Bug 63145: Rollback any open database transactions
508 if ( !( $e instanceof UsageException
) ) {
509 // UsageExceptions are intentional, so don't rollback if that's the case
511 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
512 } catch ( DBError
$e2 ) {
513 // Rollback threw an exception too. Log it, but don't interrupt
514 // our regularly scheduled exception handling.
515 MWExceptionHandler
::logException( $e2 );
519 // Allow extra cleanup and logging
520 Hooks
::run( 'ApiMain::onException', [ $this, $e ] );
523 if ( !( $e instanceof UsageException
) ) {
524 MWExceptionHandler
::logException( $e );
527 // Handle any kind of exception by outputting properly formatted error message.
528 // If this fails, an unhandled exception should be thrown so that global error
529 // handler will process and log it.
531 $errCode = $this->substituteResultWithError( $e );
533 // Error results should not be cached
534 $this->setCacheMode( 'private' );
536 $response = $this->getRequest()->response();
537 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
538 if ( $e->getCode() === 0 ) {
539 $response->header( $headerStr );
541 $response->header( $headerStr, true, $e->getCode() );
544 // Reset and print just the error message
547 // Printer may not be initialized if the extractRequestParams() fails for the main module
548 $this->createErrorPrinter();
551 $this->printResult( true );
552 } catch ( UsageException
$ex ) {
553 // The error printer itself is failing. Try suppressing its request
554 // parameters and redo.
556 'Error printer failed (will retry without params): ' . $ex->getMessage()
558 $this->mPrinter
= null;
559 $this->createErrorPrinter();
560 $this->mPrinter
->forceDefaultParams();
561 $this->printResult( true );
566 * Handle an exception from the ApiBeforeMain hook.
568 * This tries to print the exception as an API response, to be more
569 * friendly to clients. If it fails, it will rethrow the exception.
572 * @param Exception $e
575 public static function handleApiBeforeMainException( Exception
$e ) {
579 $main = new self( RequestContext
::getMain(), false );
580 $main->handleException( $e );
581 $main->logRequest( 0, $e );
582 } catch ( Exception
$e2 ) {
583 // Nope, even that didn't work. Punt.
587 // Reset cache headers
588 $main->sendCacheHeaders( true );
594 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
596 * If no origin parameter is present, nothing happens.
597 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
598 * is set and false is returned.
599 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
600 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
602 * http://www.w3.org/TR/cors/#resource-requests
603 * http://www.w3.org/TR/cors/#resource-preflight-requests
605 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
607 protected function handleCORS() {
608 $originParam = $this->getParameter( 'origin' ); // defaults to null
609 if ( $originParam === null ) {
610 // No origin parameter, nothing to do
614 $request = $this->getRequest();
615 $response = $request->response();
617 // Origin: header is a space-separated list of origins, check all of them
618 $originHeader = $request->getHeader( 'Origin' );
619 if ( $originHeader === false ) {
622 $originHeader = trim( $originHeader );
623 $origins = preg_split( '/\s+/', $originHeader );
626 if ( !in_array( $originParam, $origins ) ) {
627 // origin parameter set but incorrect
628 // Send a 403 response
629 $response->statusHeader( 403 );
630 $response->header( 'Cache-Control: no-cache' );
631 echo "'origin' parameter does not match Origin header\n";
636 $config = $this->getConfig();
637 $matchOrigin = count( $origins ) === 1 && self
::matchOrigin(
639 $config->get( 'CrossSiteAJAXdomains' ),
640 $config->get( 'CrossSiteAJAXdomainExceptions' )
643 if ( $matchOrigin ) {
644 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
645 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
647 // This is a CORS preflight request
648 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
649 // If method is not a case-sensitive match, do not set any additional headers and terminate.
652 // We allow the actual request to send the following headers
653 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
654 if ( $requestedHeaders !== false ) {
655 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
658 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
661 // We only allow the actual request to be GET or POST
662 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
665 $response->header( "Access-Control-Allow-Origin: $originHeader" );
666 $response->header( 'Access-Control-Allow-Credentials: true' );
667 // http://www.w3.org/TR/resource-timing/#timing-allow-origin
668 $response->header( "Timing-Allow-Origin: $originHeader" );
672 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag'
677 $this->getOutput()->addVaryHeader( 'Origin' );
682 * Attempt to match an Origin header against a set of rules and a set of exceptions
683 * @param string $value Origin header
684 * @param array $rules Set of wildcard rules
685 * @param array $exceptions Set of wildcard rules
686 * @return bool True if $value matches a rule in $rules and doesn't match
687 * any rules in $exceptions, false otherwise
689 protected static function matchOrigin( $value, $rules, $exceptions ) {
690 foreach ( $rules as $rule ) {
691 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
692 // Rule matches, check exceptions
693 foreach ( $exceptions as $exc ) {
694 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
707 * Attempt to validate the value of Access-Control-Request-Headers against a list
708 * of headers that we allow the follow up request to send.
710 * @param string $requestedHeaders Comma seperated list of HTTP headers
711 * @return bool True if all requested headers are in the list of allowed headers
713 protected static function matchRequestedHeaders( $requestedHeaders ) {
714 if ( trim( $requestedHeaders ) === '' ) {
717 $requestedHeaders = explode( ',', $requestedHeaders );
718 $allowedAuthorHeaders = array_flip( [
719 /* simple headers (see spec) */
724 /* non-authorable headers in XHR, which are however requested by some UAs */
728 /* MediaWiki whitelist */
731 foreach ( $requestedHeaders as $rHeader ) {
732 $rHeader = strtolower( trim( $rHeader ) );
733 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
734 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
742 * Helper function to convert wildcard string into a regex
746 * @param string $wildcard String with wildcards
747 * @return string Regular expression
749 protected static function wildcardToRegex( $wildcard ) {
750 $wildcard = preg_quote( $wildcard, '/' );
751 $wildcard = str_replace(
757 return "/^https?:\/\/$wildcard$/";
761 * Send caching headers
762 * @param bool $isError Whether an error response is being output
763 * @since 1.26 added $isError parameter
765 protected function sendCacheHeaders( $isError ) {
766 $response = $this->getRequest()->response();
767 $out = $this->getOutput();
769 $out->addVaryHeader( 'Treat-as-Untrusted' );
771 $config = $this->getConfig();
773 if ( $config->get( 'VaryOnXFP' ) ) {
774 $out->addVaryHeader( 'X-Forwarded-Proto' );
777 if ( !$isError && $this->mModule
&&
778 ( $this->getRequest()->getMethod() === 'GET' ||
$this->getRequest()->getMethod() === 'HEAD' )
780 $etag = $this->mModule
->getConditionalRequestData( 'etag' );
781 if ( $etag !== null ) {
782 $response->header( "ETag: $etag" );
784 $lastMod = $this->mModule
->getConditionalRequestData( 'last-modified' );
785 if ( $lastMod !== null ) {
786 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $lastMod ) );
790 // The logic should be:
791 // $this->mCacheControl['max-age'] is set?
792 // Use it, the module knows better than our guess.
793 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
794 // Use 0 because we can guess caching is probably the wrong thing to do.
795 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
797 if ( isset( $this->mCacheControl
['max-age'] ) ) {
798 $maxage = $this->mCacheControl
['max-age'];
799 } elseif ( ( $this->mModule
&& !$this->mModule
->isWriteMode() ) ||
800 $this->mCacheMode
!== 'private'
802 $maxage = $this->getParameter( 'maxage' );
804 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
806 if ( $this->mCacheMode
== 'private' ) {
807 $response->header( "Cache-Control: $privateCache" );
811 $useKeyHeader = $config->get( 'UseKeyHeader' );
812 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
813 $out->addVaryHeader( 'Cookie' );
814 $response->header( $out->getVaryHeader() );
815 if ( $useKeyHeader ) {
816 $response->header( $out->getKeyHeader() );
817 if ( $out->haveCacheVaryCookies() ) {
818 // Logged in, mark this request private
819 $response->header( "Cache-Control: $privateCache" );
822 // Logged out, send normal public headers below
823 } elseif ( MediaWiki\Session\SessionManager
::getGlobalSession()->isPersistent() ) {
824 // Logged in or otherwise has session (e.g. anonymous users who have edited)
825 // Mark request private
826 $response->header( "Cache-Control: $privateCache" );
829 } // else no Key and anonymous, send public headers below
832 // Send public headers
833 $response->header( $out->getVaryHeader() );
834 if ( $useKeyHeader ) {
835 $response->header( $out->getKeyHeader() );
838 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
839 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
840 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
842 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
843 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
846 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
847 // Public cache not requested
848 // Sending a Vary header in this case is harmless, and protects us
849 // against conditional calls of setCacheMaxAge().
850 $response->header( "Cache-Control: $privateCache" );
855 $this->mCacheControl
['public'] = true;
857 // Send an Expires header
858 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
859 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
860 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
862 // Construct the Cache-Control header
865 foreach ( $this->mCacheControl
as $name => $value ) {
866 if ( is_bool( $value ) ) {
868 $ccHeader .= $separator . $name;
872 $ccHeader .= $separator . "$name=$value";
877 $response->header( "Cache-Control: $ccHeader" );
881 * Create the printer for error output
883 private function createErrorPrinter() {
884 if ( !isset( $this->mPrinter
) ) {
885 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
886 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
887 $value = self
::API_DEFAULT_FORMAT
;
889 $this->mPrinter
= $this->createPrinterByName( $value );
892 // Printer may not be able to handle errors. This is particularly
893 // likely if the module returns something for getCustomPrinter().
894 if ( !$this->mPrinter
->canPrintErrors() ) {
895 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
900 * Create an error message for the given exception.
902 * If the exception is a UsageException then
903 * UsageException::getMessageArray() will be called to create the message.
905 * @param Exception $e
906 * @return array ['code' => 'some string', 'info' => 'some other string']
909 protected function errorMessageFromException( $e ) {
910 if ( $e instanceof UsageException
) {
911 // User entered incorrect parameters - generate error response
912 $errMessage = $e->getMessageArray();
914 $config = $this->getConfig();
915 // Something is seriously wrong
916 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
917 $info = 'Database query error';
919 $info = "Exception Caught: {$e->getMessage()}";
923 'code' => 'internal_api_error_' . get_class( $e ),
924 'info' => '[' . WebRequest
::getRequestId() . '] ' . $info,
931 * Replace the result data with the information about an exception.
932 * Returns the error code
933 * @param Exception $e
936 protected function substituteResultWithError( $e ) {
937 $result = $this->getResult();
938 $config = $this->getConfig();
940 $errMessage = $this->errorMessageFromException( $e );
941 if ( $e instanceof UsageException
) {
942 // User entered incorrect parameters - generate error response
943 $link = wfExpandUrl( wfScript( 'api' ) );
944 ApiResult
::setContentValue( $errMessage, 'docref', "See $link for API usage" );
946 // Something is seriously wrong
947 if ( $config->get( 'ShowExceptionDetails' ) ) {
948 ApiResult
::setContentValue(
951 MWExceptionHandler
::getRedactedTraceAsString( $e )
956 // Remember all the warnings to re-add them later
957 $warnings = $result->getResultData( [ 'warnings' ] );
961 $requestid = $this->getParameter( 'requestid' );
962 if ( !is_null( $requestid ) ) {
963 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
965 if ( $config->get( 'ShowHostnames' ) ) {
966 // servedby is especially useful when debugging errors
967 $result->addValue( null, 'servedby', wfHostname(), ApiResult
::NO_SIZE_CHECK
);
969 if ( $warnings !== null ) {
970 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
973 $result->addValue( null, 'error', $errMessage, ApiResult
::NO_SIZE_CHECK
);
975 return $errMessage['code'];
979 * Set up for the execution.
982 protected function setupExecuteAction() {
983 // First add the id to the top element
984 $result = $this->getResult();
985 $requestid = $this->getParameter( 'requestid' );
986 if ( !is_null( $requestid ) ) {
987 $result->addValue( null, 'requestid', $requestid );
990 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
991 $servedby = $this->getParameter( 'servedby' );
993 $result->addValue( null, 'servedby', wfHostname() );
997 if ( $this->getParameter( 'curtimestamp' ) ) {
998 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
999 ApiResult
::NO_SIZE_CHECK
);
1002 $params = $this->extractRequestParams();
1004 $this->mAction
= $params['action'];
1006 if ( !is_string( $this->mAction
) ) {
1007 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1014 * Set up the module for response
1015 * @return ApiBase The module that will handle this action
1016 * @throws MWException
1017 * @throws UsageException
1019 protected function setupModule() {
1020 // Instantiate the module requested by the user
1021 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
1022 if ( $module === null ) {
1023 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
1025 $moduleParams = $module->extractRequestParams();
1027 // Check token, if necessary
1028 if ( $module->needsToken() === true ) {
1029 throw new MWException(
1030 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
1031 'See documentation for ApiBase::needsToken for details.'
1034 if ( $module->needsToken() ) {
1035 if ( !$module->mustBePosted() ) {
1036 throw new MWException(
1037 "Module '{$module->getModuleName()}' must require POST to use tokens."
1041 if ( !isset( $moduleParams['token'] ) ) {
1042 $this->dieUsageMsg( [ 'missingparam', 'token' ] );
1045 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
1047 $module->encodeParamName( 'token' ),
1048 $this->getRequest()->getQueryValues()
1052 "The '{$module->encodeParamName( 'token' )}' parameter was " .
1053 'found in the query string, but must be in the POST body',
1058 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
1059 $this->dieUsageMsg( 'sessionfailure' );
1067 * Check the max lag if necessary
1068 * @param ApiBase $module Api module being used
1069 * @param array $params Array an array containing the request parameters.
1070 * @return bool True on success, false should exit immediately
1072 protected function checkMaxLag( $module, $params ) {
1073 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1074 $maxLag = $params['maxlag'];
1075 list( $host, $lag ) = wfGetLB()->getMaxLag();
1076 if ( $lag > $maxLag ) {
1077 $response = $this->getRequest()->response();
1079 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1080 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
1082 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1083 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
1086 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
1094 * Check selected RFC 7232 precondition headers
1096 * RFC 7232 envisions a particular model where you send your request to "a
1097 * resource", and for write requests that you can read "the resource" by
1098 * changing the method to GET. When the API receives a GET request, it
1099 * works out even though "the resource" from RFC 7232's perspective might
1100 * be many resources from MediaWiki's perspective. But it totally fails for
1101 * a POST, since what HTTP sees as "the resource" is probably just
1102 * "/api.php" with all the interesting bits in the body.
1104 * Therefore, we only support RFC 7232 precondition headers for GET (and
1105 * HEAD). That means we don't need to bother with If-Match and
1106 * If-Unmodified-Since since they only apply to modification requests.
1108 * And since we don't support Range, If-Range is ignored too.
1111 * @param ApiBase $module Api module being used
1112 * @return bool True on success, false should exit immediately
1114 protected function checkConditionalRequestHeaders( $module ) {
1115 if ( $this->mInternalMode
) {
1116 // No headers to check in internal mode
1120 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1121 // Don't check POSTs
1127 $ifNoneMatch = array_diff(
1128 $this->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
) ?
: [],
1131 if ( $ifNoneMatch ) {
1132 if ( $ifNoneMatch === [ '*' ] ) {
1133 // API responses always "exist"
1136 $etag = $module->getConditionalRequestData( 'etag' );
1139 if ( $ifNoneMatch && $etag !== null ) {
1140 $test = substr( $etag, 0, 2 ) === 'W/' ?
substr( $etag, 2 ) : $etag;
1141 $match = array_map( function ( $s ) {
1142 return substr( $s, 0, 2 ) === 'W/' ?
substr( $s, 2 ) : $s;
1144 $return304 = in_array( $test, $match, true );
1146 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1148 // Some old browsers sends sizes after the date, like this:
1149 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1151 $i = strpos( $value, ';' );
1152 if ( $i !== false ) {
1153 $value = trim( substr( $value, 0, $i ) );
1156 if ( $value !== '' ) {
1158 $ts = new MWTimestamp( $value );
1160 // RFC 7231 IMF-fixdate
1161 $ts->getTimestamp( TS_RFC2822
) === $value ||
1163 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1164 // asctime (with and without space-padded day)
1165 $ts->format( 'D M j H:i:s Y' ) === $value ||
1166 $ts->format( 'D M j H:i:s Y' ) === $value
1168 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1169 if ( $lastMod !== null ) {
1170 // Mix in some MediaWiki modification times
1173 'user' => $this->getUser()->getTouched(),
1174 'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1176 if ( $this->getConfig()->get( 'UseSquid' ) ) {
1177 // T46570: the core page itself may not change, but resources might
1178 $modifiedTimes['sepoch'] = wfTimestamp(
1179 TS_MW
, time() - $this->getConfig()->get( 'SquidMaxage' )
1182 Hooks
::run( 'OutputPageCheckLastModified', [ &$modifiedTimes, $this->getOutput() ] );
1183 $lastMod = max( $modifiedTimes );
1184 $return304 = wfTimestamp( TS_MW
, $lastMod ) <= $ts->getTimestamp( TS_MW
);
1187 } catch ( TimestampException
$e ) {
1188 // Invalid timestamp, ignore it
1194 $this->getRequest()->response()->statusHeader( 304 );
1196 // Avoid outputting the compressed representation of a zero-length body
1197 MediaWiki\
suppressWarnings();
1198 ini_set( 'zlib.output_compression', 0 );
1199 MediaWiki\restoreWarnings
();
1200 wfClearOutputBuffers();
1209 * Check for sufficient permissions to execute
1210 * @param ApiBase $module An Api module
1212 protected function checkExecutePermissions( $module ) {
1213 $user = $this->getUser();
1214 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
1215 !$user->isAllowed( 'read' )
1217 $this->dieUsageMsg( 'readrequired' );
1220 if ( $module->isWriteMode() ) {
1221 if ( !$this->mEnableWrite
) {
1222 $this->dieUsageMsg( 'writedisabled' );
1223 } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1224 $this->dieUsageMsg( 'writerequired' );
1225 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1227 'Promise-Non-Write-API-Action HTTP header cannot be sent to write API modules',
1228 'promised-nonwrite-api'
1232 $this->checkReadOnly( $module );
1235 // Allow extensions to stop execution for arbitrary reasons.
1237 if ( !Hooks
::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) {
1238 $this->dieUsageMsg( $message );
1243 * Check if the DB is read-only for this user
1244 * @param ApiBase $module An Api module
1246 protected function checkReadOnly( $module ) {
1247 if ( wfReadOnly() ) {
1248 $this->dieReadOnly();
1251 if ( $module->isWriteMode()
1252 && in_array( 'bot', $this->getUser()->getGroups() )
1253 && wfGetLB()->getServerCount() > 1
1255 $this->checkBotReadOnly();
1260 * Check whether we are readonly for bots
1262 private function checkBotReadOnly() {
1263 // Figure out how many servers have passed the lag threshold
1265 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1266 $laggedServers = [];
1267 $loadBalancer = wfGetLB();
1268 foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) {
1269 if ( $lag > $lagLimit ) {
1271 $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)";
1275 // If a majority of slaves are too lagged then disallow writes
1276 $slaveCount = wfGetLB()->getServerCount() - 1;
1277 if ( $numLagged >= ceil( $slaveCount / 2 ) ) {
1278 $laggedServers = implode( ', ', $laggedServers );
1281 "Api request failed as read only because the following DBs are lagged: $laggedServers"
1284 $parsed = $this->parseMsg( [ 'readonlytext' ] );
1290 [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ]
1296 * Check asserts of the user's rights
1297 * @param array $params
1299 protected function checkAsserts( $params ) {
1300 if ( isset( $params['assert'] ) ) {
1301 $user = $this->getUser();
1302 switch ( $params['assert'] ) {
1304 if ( $user->isAnon() ) {
1305 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
1309 if ( !$user->isAllowed( 'bot' ) ) {
1310 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1318 * Check POST for external response and setup result printer
1319 * @param ApiBase $module An Api module
1320 * @param array $params An array with the request parameters
1322 protected function setupExternalResponse( $module, $params ) {
1323 $request = $this->getRequest();
1324 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1325 // Module requires POST. GET request might still be allowed
1326 // if $wgDebugApi is true, otherwise fail.
1327 $this->dieUsageMsgOrDebug( [ 'mustbeposted', $this->mAction
] );
1330 // See if custom printer is used
1331 $this->mPrinter
= $module->getCustomPrinter();
1332 if ( is_null( $this->mPrinter
) ) {
1333 // Create an appropriate printer
1334 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1337 if ( $request->getProtocol() === 'http' && (
1338 $request->getSession()->shouldForceHTTPS() ||
1339 ( $this->getUser()->isLoggedIn() &&
1340 $this->getUser()->requiresHTTPS() )
1342 $this->logFeatureUsage( 'https-expected' );
1343 $this->setWarning( 'HTTP used when HTTPS was expected' );
1348 * Execute the actual module, without any error handling
1350 protected function executeAction() {
1351 $params = $this->setupExecuteAction();
1352 $module = $this->setupModule();
1353 $this->mModule
= $module;
1355 if ( !$this->mInternalMode
) {
1356 $this->setRequestExpectations( $module );
1359 $this->checkExecutePermissions( $module );
1361 if ( !$this->checkMaxLag( $module, $params ) ) {
1365 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1369 if ( !$this->mInternalMode
) {
1370 $this->setupExternalResponse( $module, $params );
1373 $this->checkAsserts( $params );
1377 Hooks
::run( 'APIAfterExecute', [ &$module ] );
1379 $this->reportUnusedParams();
1381 if ( !$this->mInternalMode
) {
1382 // append Debug information
1383 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1385 // Print result data
1386 $this->printResult( false );
1391 * Set database connection, query, and write expectations given this module request
1392 * @param ApiBase $module
1394 protected function setRequestExpectations( ApiBase
$module ) {
1395 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1396 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1397 if ( $this->getRequest()->hasSafeMethod() ) {
1398 $trxProfiler->setExpectations( $limits['GET'], __METHOD__
);
1399 } elseif ( $this->getRequest()->wasPosted() && !$module->isWriteMode() ) {
1400 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__
);
1401 $this->getRequest()->markAsSafeRequest();
1403 $trxProfiler->setExpectations( $limits['POST'], __METHOD__
);
1408 * Log the preceding request
1409 * @param float $time Time in seconds
1410 * @param Exception $e Exception caught while processing the request
1412 protected function logRequest( $time, $e = null ) {
1413 $request = $this->getRequest();
1416 'ip' => $request->getIP(),
1417 'userAgent' => $this->getUserAgent(),
1418 'wiki' => wfWikiID(),
1419 'timeSpentBackend' => (int) round( $time * 1000 ),
1420 'hadError' => $e !== null,
1426 $logCtx['errorCodes'][] = $this->errorMessageFromException( $e )['code'];
1429 // Construct space separated message for 'api' log channel
1430 $msg = "API {$request->getMethod()} " .
1431 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1432 " {$logCtx['ip']} " .
1433 "T={$logCtx['timeSpentBackend']}ms";
1435 foreach ( $this->getParamsUsed() as $name ) {
1436 $value = $request->getVal( $name );
1437 if ( $value === null ) {
1441 if ( strlen( $value ) > 256 ) {
1442 $value = substr( $value, 0, 256 );
1443 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1445 $encValue = $this->encodeRequestLogValue( $value );
1448 $logCtx['params'][$name] = $value;
1449 $msg .= " {$name}={$encValue}";
1452 wfDebugLog( 'api', $msg, 'private' );
1453 // ApiAction channel is for structured data consumers
1454 wfDebugLog( 'ApiAction', '', 'private', $logCtx );
1458 * Encode a value in a format suitable for a space-separated log line.
1462 protected function encodeRequestLogValue( $s ) {
1465 $chars = ';@$!*(),/:';
1466 $numChars = strlen( $chars );
1467 for ( $i = 0; $i < $numChars; $i++
) {
1468 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1472 return strtr( rawurlencode( $s ), $table );
1476 * Get the request parameters used in the course of the preceding execute() request
1479 protected function getParamsUsed() {
1480 return array_keys( $this->mParamsUsed
);
1484 * Mark parameters as used
1485 * @param string|string[] $params
1487 public function markParamsUsed( $params ) {
1488 $this->mParamsUsed +
= array_fill_keys( (array)$params, true );
1492 * Get a request value, and register the fact that it was used, for logging.
1493 * @param string $name
1494 * @param mixed $default
1497 public function getVal( $name, $default = null ) {
1498 $this->mParamsUsed
[$name] = true;
1500 $ret = $this->getRequest()->getVal( $name );
1501 if ( $ret === null ) {
1502 if ( $this->getRequest()->getArray( $name ) !== null ) {
1503 // See bug 10262 for why we don't just implode( '|', ... ) the
1506 "Parameter '$name' uses unsupported PHP array syntax"
1515 * Get a boolean request value, and register the fact that the parameter
1516 * was used, for logging.
1517 * @param string $name
1520 public function getCheck( $name ) {
1521 return $this->getVal( $name, null ) !== null;
1525 * Get a request upload, and register the fact that it was used, for logging.
1528 * @param string $name Parameter name
1529 * @return WebRequestUpload
1531 public function getUpload( $name ) {
1532 $this->mParamsUsed
[$name] = true;
1534 return $this->getRequest()->getUpload( $name );
1538 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1539 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1541 protected function reportUnusedParams() {
1542 $paramsUsed = $this->getParamsUsed();
1543 $allParams = $this->getRequest()->getValueNames();
1545 if ( !$this->mInternalMode
) {
1546 // Printer has not yet executed; don't warn that its parameters are unused
1547 $printerParams = array_map(
1548 [ $this->mPrinter
, 'encodeParamName' ],
1549 array_keys( $this->mPrinter
->getFinalParams() ?
: [] )
1551 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1553 $unusedParams = array_diff( $allParams, $paramsUsed );
1556 if ( count( $unusedParams ) ) {
1557 $s = count( $unusedParams ) > 1 ?
's' : '';
1558 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1563 * Print results using the current printer
1565 * @param bool $isError
1567 protected function printResult( $isError ) {
1568 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1569 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1572 $printer = $this->mPrinter
;
1573 $printer->initPrinter( false );
1574 $printer->execute();
1575 $printer->closePrinter();
1581 public function isReadMode() {
1586 * See ApiBase for description.
1590 public function getAllowedParams() {
1593 ApiBase
::PARAM_DFLT
=> 'help',
1594 ApiBase
::PARAM_TYPE
=> 'submodule',
1597 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1598 ApiBase
::PARAM_TYPE
=> 'submodule',
1601 ApiBase
::PARAM_TYPE
=> 'integer'
1604 ApiBase
::PARAM_TYPE
=> 'integer',
1605 ApiBase
::PARAM_DFLT
=> 0
1608 ApiBase
::PARAM_TYPE
=> 'integer',
1609 ApiBase
::PARAM_DFLT
=> 0
1612 ApiBase
::PARAM_TYPE
=> [ 'user', 'bot' ]
1614 'requestid' => null,
1615 'servedby' => false,
1616 'curtimestamp' => false,
1619 ApiBase
::PARAM_DFLT
=> 'user',
1624 /** @see ApiBase::getExamplesMessages() */
1625 protected function getExamplesMessages() {
1628 => 'apihelp-help-example-main',
1629 'action=help&recursivesubmodules=1'
1630 => 'apihelp-help-example-recursive',
1634 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1635 // Wish PHP had an "array_insert_before". Instead, we have to manually
1636 // reindex the array to get 'permissions' in the right place.
1639 foreach ( $oldHelp as $k => $v ) {
1640 if ( $k === 'submodules' ) {
1641 $help['permissions'] = '';
1645 $help['datatypes'] = '';
1646 $help['credits'] = '';
1648 // Fill 'permissions'
1649 $help['permissions'] .= Html
::openElement( 'div',
1650 [ 'class' => 'apihelp-block apihelp-permissions' ] );
1651 $m = $this->msg( 'api-help-permissions' );
1652 if ( !$m->isDisabled() ) {
1653 $help['permissions'] .= Html
::rawElement( 'div', [ 'class' => 'apihelp-block-head' ],
1654 $m->numParams( count( self
::$mRights ) )->parse()
1657 $help['permissions'] .= Html
::openElement( 'dl' );
1658 foreach ( self
::$mRights as $right => $rightMsg ) {
1659 $help['permissions'] .= Html
::element( 'dt', null, $right );
1661 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1662 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1664 $groups = array_map( function ( $group ) {
1665 return $group == '*' ?
'all' : $group;
1666 }, User
::getGroupsWithPermission( $right ) );
1668 $help['permissions'] .= Html
::rawElement( 'dd', null,
1669 $this->msg( 'api-help-permissions-granted-to' )
1670 ->numParams( count( $groups ) )
1671 ->params( $this->getLanguage()->commaList( $groups ) )
1675 $help['permissions'] .= Html
::closeElement( 'dl' );
1676 $help['permissions'] .= Html
::closeElement( 'div' );
1678 // Fill 'datatypes' and 'credits', if applicable
1679 if ( empty( $options['nolead'] ) ) {
1680 $level = $options['headerlevel'];
1681 $tocnumber = &$options['tocnumber'];
1683 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1685 // Add an additional span with sanitized ID
1686 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1687 $header = Html
::element( 'span', [ 'id' => Sanitizer
::escapeId( 'main/datatypes' ) ] ) .
1690 $help['datatypes'] .= Html
::rawElement( 'h' . min( 6, $level ),
1691 [ 'id' => 'main/datatypes', 'class' => 'apihelp-header' ],
1694 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1695 if ( !isset( $tocData['main/datatypes'] ) ) {
1696 $tocnumber[$level]++
;
1697 $tocData['main/datatypes'] = [
1698 'toclevel' => count( $tocnumber ),
1700 'anchor' => 'main/datatypes',
1702 'number' => implode( '.', $tocnumber ),
1707 // Add an additional span with sanitized ID
1708 if ( !$this->getConfig()->get( 'ExperimentalHtmlIds' ) ) {
1709 $header = Html
::element( 'span', [ 'id' => Sanitizer
::escapeId( 'main/credits' ) ] ) .
1712 $header = $this->msg( 'api-credits-header' )->parse();
1713 $help['credits'] .= Html
::rawElement( 'h' . min( 6, $level ),
1714 [ 'id' => 'main/credits', 'class' => 'apihelp-header' ],
1717 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1718 if ( !isset( $tocData['main/credits'] ) ) {
1719 $tocnumber[$level]++
;
1720 $tocData['main/credits'] = [
1721 'toclevel' => count( $tocnumber ),
1723 'anchor' => 'main/credits',
1725 'number' => implode( '.', $tocnumber ),
1732 private $mCanApiHighLimits = null;
1735 * Check whether the current user is allowed to use high limits
1738 public function canApiHighLimits() {
1739 if ( !isset( $this->mCanApiHighLimits
) ) {
1740 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1743 return $this->mCanApiHighLimits
;
1747 * Overrides to return this instance's module manager.
1748 * @return ApiModuleManager
1750 public function getModuleManager() {
1751 return $this->mModuleMgr
;
1755 * Fetches the user agent used for this request
1757 * The value will be the combination of the 'Api-User-Agent' header (if
1758 * any) and the standard User-Agent header (if any).
1762 public function getUserAgent() {
1764 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1765 $this->getRequest()->getHeader( 'User-agent' )
1769 /************************************************************************//**
1775 * Sets whether the pretty-printer should format *bold* and $italics$
1777 * @deprecated since 1.25
1780 public function setHelp( $help = true ) {
1781 wfDeprecated( __METHOD__
, '1.25' );
1782 $this->mPrinter
->setHelp( $help );
1786 * Override the parent to generate help messages for all available modules.
1788 * @deprecated since 1.25
1791 public function makeHelpMsg() {
1792 wfDeprecated( __METHOD__
, '1.25' );
1795 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1797 return ObjectCache
::getMainWANInstance()->getWithSetCallback(
1800 $this->getModuleName(),
1801 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) )
1803 $cacheHelpTimeout > 0 ?
$cacheHelpTimeout : WANObjectCache
::TTL_UNCACHEABLE
,
1804 [ $this, 'reallyMakeHelpMsg' ]
1809 * @deprecated since 1.25
1810 * @return mixed|string
1812 public function reallyMakeHelpMsg() {
1813 wfDeprecated( __METHOD__
, '1.25' );
1816 // Use parent to make default message for the main module
1817 $msg = parent
::makeHelpMsg();
1819 $asterisks = str_repeat( '*** ', 14 );
1820 $msg .= "\n\n$asterisks Modules $asterisks\n\n";
1822 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1823 $module = $this->mModuleMgr
->getModule( $name );
1824 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1826 $msg2 = $module->makeHelpMsg();
1827 if ( $msg2 !== false ) {
1833 $msg .= "\n$asterisks Permissions $asterisks\n\n";
1834 foreach ( self
::$mRights as $right => $rightMsg ) {
1835 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1836 ->useDatabase( false )
1837 ->inLanguage( 'en' )
1839 $groups = User
::getGroupsWithPermission( $right );
1840 $msg .= '* ' . $right . " *\n $rightsMsg" .
1841 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1844 $msg .= "\n$asterisks Formats $asterisks\n\n";
1845 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1846 $module = $this->mModuleMgr
->getModule( $name );
1847 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1848 $msg2 = $module->makeHelpMsg();
1849 if ( $msg2 !== false ) {
1855 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1856 $credits = str_replace( "\n", "\n ", $credits );
1857 $msg .= "\n*** Credits: ***\n $credits\n";
1863 * @deprecated since 1.25
1864 * @param ApiBase $module
1865 * @param string $paramName What type of request is this? e.g. action,
1866 * query, list, prop, meta, format
1869 public static function makeHelpMsgHeader( $module, $paramName ) {
1870 wfDeprecated( __METHOD__
, '1.25' );
1871 $modulePrefix = $module->getModulePrefix();
1872 if ( strval( $modulePrefix ) !== '' ) {
1873 $modulePrefix = "($modulePrefix) ";
1876 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1884 * This exception will be thrown when dieUsage is called to stop module execution.
1888 class UsageException
extends MWException
{
1895 private $mExtraData;
1898 * @param string $message
1899 * @param string $codestr
1901 * @param array|null $extradata
1903 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1904 parent
::__construct( $message, $code );
1905 $this->mCodestr
= $codestr;
1906 $this->mExtraData
= $extradata;
1908 // This should never happen, so throw an exception about it that will
1909 // hopefully get logged with a backtrace (T138585)
1910 if ( !is_string( $codestr ) ||
$codestr === '' ) {
1911 throw new InvalidArgumentException( 'Invalid $codestr, was ' .
1912 ( $codestr === '' ?
'empty string' : gettype( $codestr ) )
1920 public function getCodeString() {
1921 return $this->mCodestr
;
1927 public function getMessageArray() {
1929 'code' => $this->mCodestr
,
1930 'info' => $this->getMessage()
1932 if ( is_array( $this->mExtraData
) ) {
1933 $result = array_merge( $result, $this->mExtraData
);
1942 public function __toString() {
1943 return "{$this->getCodeString()}: {$this->getMessage()}";
1948 * For really cool vim folding this needs to be at the end:
1949 * vim: foldmarker=@{,@} foldmethod=marker