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 = array(
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',
96 * List of available formats: format name => format class
98 private static $Formats = array(
99 'json' => 'ApiFormatJson',
100 'jsonfm' => 'ApiFormatJson',
101 'php' => 'ApiFormatPhp',
102 'phpfm' => 'ApiFormatPhp',
103 'wddx' => 'ApiFormatWddx',
104 'wddxfm' => 'ApiFormatWddx',
105 'xml' => 'ApiFormatXml',
106 'xmlfm' => 'ApiFormatXml',
107 'yaml' => 'ApiFormatYaml',
108 'yamlfm' => 'ApiFormatYaml',
109 'rawfm' => 'ApiFormatJson',
110 'txt' => 'ApiFormatTxt',
111 'txtfm' => 'ApiFormatTxt',
112 'dbg' => 'ApiFormatDbg',
113 'dbgfm' => 'ApiFormatDbg',
114 'dump' => 'ApiFormatDump',
115 'dumpfm' => 'ApiFormatDump',
116 'none' => 'ApiFormatNone',
119 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
121 * List of user roles that are specifically relevant to the API.
122 * array( 'right' => array ( 'msg' => 'Some message with a $1',
123 * 'params' => array ( $someVarToSubst ) ),
126 private static $mRights = array(
128 'msg' => 'right-writeapi',
131 'apihighlimits' => array(
132 'msg' => 'api-help-right-apihighlimits',
133 'params' => array( ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
)
136 // @codingStandardsIgnoreEnd
143 private $mModuleMgr, $mResult;
145 private $mEnableWrite;
146 private $mInternalMode, $mSquidMaxage, $mModule;
148 private $mCacheMode = 'private';
149 private $mCacheControl = array();
150 private $mParamsUsed = array();
153 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
155 * @param IContextSource|WebRequest $context If this is an instance of
156 * FauxRequest, errors are thrown and no printing occurs
157 * @param bool $enableWrite Should be set to true if the api may modify data
159 public function __construct( $context = null, $enableWrite = false ) {
160 if ( $context === null ) {
161 $context = RequestContext
::getMain();
162 } elseif ( $context instanceof WebRequest
) {
165 $context = RequestContext
::getMain();
167 // We set a derivative context so we can change stuff later
168 $this->setContext( new DerivativeContext( $context ) );
170 if ( isset( $request ) ) {
171 $this->getContext()->setRequest( $request );
174 $this->mInternalMode
= ( $this->getRequest() instanceof FauxRequest
);
176 // Special handling for the main module: $parent === $this
177 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
179 if ( !$this->mInternalMode
) {
180 // Impose module restrictions.
181 // If the current user cannot read,
182 // Remove all modules other than login
185 if ( $this->lacksSameOriginSecurity() ) {
186 // If we're in a mode that breaks the same-origin policy, strip
187 // user credentials for security.
188 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
189 $wgUser = new User();
190 $this->getContext()->setUser( $wgUser );
194 $uselang = $this->getParameter( 'uselang' );
195 if ( $uselang === 'user' ) {
196 // Assume the parent context is going to return the user language
197 // for uselang=user (see T85635).
199 if ( $uselang === 'content' ) {
201 $uselang = $wgContLang->getCode();
203 $code = RequestContext
::sanitizeLangCode( $uselang );
204 $this->getContext()->setLanguage( $code );
205 if ( !$this->mInternalMode
) {
207 $wgLang = $this->getContext()->getLanguage();
208 RequestContext
::getMain()->setLanguage( $wgLang );
212 $config = $this->getConfig();
213 $this->mModuleMgr
= new ApiModuleManager( $this );
214 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
215 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
216 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
217 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
219 Hooks
::run( 'ApiMain::moduleManager', array( $this->mModuleMgr
) );
221 $this->mResult
= new ApiResult( $this );
222 $this->mEnableWrite
= $enableWrite;
224 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
225 $this->mCommit
= false;
229 * Return true if the API was started by other PHP code using FauxRequest
232 public function isInternalMode() {
233 return $this->mInternalMode
;
237 * Get the ApiResult object associated with current request
241 public function getResult() {
242 return $this->mResult
;
246 * Get the API module object. Only works after executeAction()
250 public function getModule() {
251 return $this->mModule
;
255 * Get the result formatter object. Only works after setupExecuteAction()
257 * @return ApiFormatBase
259 public function getPrinter() {
260 return $this->mPrinter
;
264 * Set how long the response should be cached.
268 public function setCacheMaxAge( $maxage ) {
269 $this->setCacheControl( array(
270 'max-age' => $maxage,
271 's-maxage' => $maxage
276 * Set the type of caching headers which will be sent.
278 * @param string $mode One of:
279 * - 'public': Cache this object in public caches, if the maxage or smaxage
280 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
281 * not provided by any of these means, the object will be private.
282 * - 'private': Cache this object only in private client-side caches.
283 * - 'anon-public-user-private': Make this object cacheable for logged-out
284 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
285 * set consistently for a given URL, it cannot be set differently depending on
286 * things like the contents of the database, or whether the user is logged in.
288 * If the wiki does not allow anonymous users to read it, the mode set here
289 * will be ignored, and private caching headers will always be sent. In other words,
290 * the "public" mode is equivalent to saying that the data sent is as public as a page
293 * For user-dependent data, the private mode should generally be used. The
294 * anon-public-user-private mode should only be used where there is a particularly
295 * good performance reason for caching the anonymous response, but where the
296 * response to logged-in users may differ, or may contain private data.
298 * If this function is never called, then the default will be the private mode.
300 public function setCacheMode( $mode ) {
301 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
302 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
304 // Ignore for forwards-compatibility
308 if ( !User
::isEveryoneAllowed( 'read' ) ) {
309 // Private wiki, only private headers
310 if ( $mode !== 'private' ) {
311 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
317 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
318 // User language is used for i18n, so we don't want to publicly
319 // cache. Anons are ok, because if they have non-default language
320 // then there's an appropriate Vary header set by whatever set
321 // their non-default language.
322 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
323 "'anon-public-user-private' due to uselang=user\n" );
324 $mode = 'anon-public-user-private';
327 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
328 $this->mCacheMode
= $mode;
332 * Set directives (key/value pairs) for the Cache-Control header.
333 * Boolean values will be formatted as such, by including or omitting
334 * without an equals sign.
336 * Cache control values set here will only be used if the cache mode is not
337 * private, see setCacheMode().
339 * @param array $directives
341 public function setCacheControl( $directives ) {
342 $this->mCacheControl
= $directives +
$this->mCacheControl
;
346 * Create an instance of an output formatter by its name
348 * @param string $format
350 * @return ApiFormatBase
352 public function createPrinterByName( $format ) {
353 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
354 if ( $printer === null ) {
355 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
362 * Execute api request. Any errors will be handled if the API was called by the remote client.
364 public function execute() {
365 if ( $this->mInternalMode
) {
366 $this->executeAction();
368 $this->executeActionWithErrorHandling();
373 * Execute an action, and in case of an error, erase whatever partial results
374 * have been accumulated, and replace it with an error message and a help screen.
376 protected function executeActionWithErrorHandling() {
377 // Verify the CORS header before executing the action
378 if ( !$this->handleCORS() ) {
379 // handleCORS() has sent a 403, abort
383 // Exit here if the request method was OPTIONS
384 // (assume there will be a followup GET or POST)
385 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
389 // In case an error occurs during data output,
390 // clear the output buffer and print just the error information
393 $t = microtime( true );
395 $this->executeAction();
396 } catch ( Exception
$e ) {
397 $this->handleException( $e );
400 // Log the request whether or not there was an error
401 $this->logRequest( microtime( true ) - $t );
403 // Send cache headers after any code which might generate an error, to
404 // avoid sending public cache headers for errors.
405 $this->sendCacheHeaders();
411 * Handle an exception as an API response
414 * @param Exception $e
416 protected function handleException( Exception
$e ) {
417 // Bug 63145: Rollback any open database transactions
418 if ( !( $e instanceof UsageException
) ) {
419 // UsageExceptions are intentional, so don't rollback if that's the case
421 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
422 } catch ( DBError
$e2 ) {
423 // Rollback threw an exception too. Log it, but don't interrupt
424 // our regularly scheduled exception handling.
425 MWExceptionHandler
::logException( $e2 );
429 // Allow extra cleanup and logging
430 Hooks
::run( 'ApiMain::onException', array( $this, $e ) );
433 if ( !( $e instanceof UsageException
) ) {
434 MWExceptionHandler
::logException( $e );
437 // Handle any kind of exception by outputting properly formatted error message.
438 // If this fails, an unhandled exception should be thrown so that global error
439 // handler will process and log it.
441 $errCode = $this->substituteResultWithError( $e );
443 // Error results should not be cached
444 $this->setCacheMode( 'private' );
446 $response = $this->getRequest()->response();
447 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
448 if ( $e->getCode() === 0 ) {
449 $response->header( $headerStr );
451 $response->header( $headerStr, true, $e->getCode() );
454 // Reset and print just the error message
457 $this->printResult( true );
461 * Handle an exception from the ApiBeforeMain hook.
463 * This tries to print the exception as an API response, to be more
464 * friendly to clients. If it fails, it will rethrow the exception.
467 * @param Exception $e
470 public static function handleApiBeforeMainException( Exception
$e ) {
474 $main = new self( RequestContext
::getMain(), false );
475 $main->handleException( $e );
476 } catch ( Exception
$e2 ) {
477 // Nope, even that didn't work. Punt.
481 // Log the request and reset cache headers
482 $main->logRequest( 0 );
483 $main->sendCacheHeaders();
489 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
491 * If no origin parameter is present, nothing happens.
492 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
493 * is set and false is returned.
494 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
495 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
497 * http://www.w3.org/TR/cors/#resource-requests
498 * http://www.w3.org/TR/cors/#resource-preflight-requests
500 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
502 protected function handleCORS() {
503 $originParam = $this->getParameter( 'origin' ); // defaults to null
504 if ( $originParam === null ) {
505 // No origin parameter, nothing to do
509 $request = $this->getRequest();
510 $response = $request->response();
512 // Origin: header is a space-separated list of origins, check all of them
513 $originHeader = $request->getHeader( 'Origin' );
514 if ( $originHeader === false ) {
517 $originHeader = trim( $originHeader );
518 $origins = preg_split( '/\s+/', $originHeader );
521 if ( !in_array( $originParam, $origins ) ) {
522 // origin parameter set but incorrect
523 // Send a 403 response
524 $message = HttpStatus
::getMessage( 403 );
525 $response->header( "HTTP/1.1 403 $message", true, 403 );
526 $response->header( 'Cache-Control: no-cache' );
527 echo "'origin' parameter does not match Origin header\n";
532 $config = $this->getConfig();
533 $matchOrigin = count( $origins ) === 1 && self
::matchOrigin(
535 $config->get( 'CrossSiteAJAXdomains' ),
536 $config->get( 'CrossSiteAJAXdomainExceptions' )
539 if ( $matchOrigin ) {
540 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
541 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
543 // This is a CORS preflight request
544 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
545 // If method is not a case-sensitive match, do not set any additional headers and terminate.
548 // We allow the actual request to send the following headers
549 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
550 if ( $requestedHeaders !== false ) {
551 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
554 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
557 // We only allow the actual request to be GET or POST
558 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
561 $response->header( "Access-Control-Allow-Origin: $originHeader" );
562 $response->header( 'Access-Control-Allow-Credentials: true' );
563 $response->header( "Timing-Allow-Origin: $originHeader" ); # http://www.w3.org/TR/resource-timing/#timing-allow-origin
566 $response->header( 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag' );
570 $this->getOutput()->addVaryHeader( 'Origin' );
575 * Attempt to match an Origin header against a set of rules and a set of exceptions
576 * @param string $value Origin header
577 * @param array $rules Set of wildcard rules
578 * @param array $exceptions Set of wildcard rules
579 * @return bool True if $value matches a rule in $rules and doesn't match
580 * any rules in $exceptions, false otherwise
582 protected static function matchOrigin( $value, $rules, $exceptions ) {
583 foreach ( $rules as $rule ) {
584 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
585 // Rule matches, check exceptions
586 foreach ( $exceptions as $exc ) {
587 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
600 * Attempt to validate the value of Access-Control-Request-Headers against a list
601 * of headers that we allow the follow up request to send.
603 * @param string $requestedHeaders Comma seperated list of HTTP headers
604 * @return bool True if all requested headers are in the list of allowed headers
606 protected static function matchRequestedHeaders( $requestedHeaders ) {
607 if ( trim( $requestedHeaders ) === '' ) {
610 $requestedHeaders = explode( ',', $requestedHeaders );
611 $allowedAuthorHeaders = array_flip( array(
612 /* simple headers (see spec) */
617 /* non-authorable headers in XHR, which are however requested by some UAs */
621 /* MediaWiki whitelist */
624 foreach ( $requestedHeaders as $rHeader ) {
625 $rHeader = strtolower( trim( $rHeader ) );
626 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
627 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
635 * Helper function to convert wildcard string into a regex
639 * @param string $wildcard String with wildcards
640 * @return string Regular expression
642 protected static function wildcardToRegex( $wildcard ) {
643 $wildcard = preg_quote( $wildcard, '/' );
644 $wildcard = str_replace(
650 return "/^https?:\/\/$wildcard$/";
653 protected function sendCacheHeaders() {
654 $response = $this->getRequest()->response();
655 $out = $this->getOutput();
657 $config = $this->getConfig();
659 if ( $config->get( 'VaryOnXFP' ) ) {
660 $out->addVaryHeader( 'X-Forwarded-Proto' );
663 // The logic should be:
664 // $this->mCacheControl['max-age'] is set?
665 // Use it, the module knows better than our guess.
666 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
667 // Use 0 because we can guess caching is probably the wrong thing to do.
668 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
670 if ( isset( $this->mCacheControl
['max-age'] ) ) {
671 $maxage = $this->mCacheControl
['max-age'];
672 } elseif ( ( $this->mModule
&& !$this->mModule
->isWriteMode() ) ||
673 $this->mCacheMode
!== 'private'
675 $maxage = $this->getParameter( 'maxage' );
677 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
679 if ( $this->mCacheMode
== 'private' ) {
680 $response->header( "Cache-Control: $privateCache" );
684 $useXVO = $config->get( 'UseXVO' );
685 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
686 $out->addVaryHeader( 'Cookie' );
687 $response->header( $out->getVaryHeader() );
689 $response->header( $out->getXVO() );
690 if ( $out->haveCacheVaryCookies() ) {
691 // Logged in, mark this request private
692 $response->header( "Cache-Control: $privateCache" );
695 // Logged out, send normal public headers below
696 } elseif ( session_id() != '' ) {
697 // Logged in or otherwise has session (e.g. anonymous users who have edited)
698 // Mark request private
699 $response->header( "Cache-Control: $privateCache" );
702 } // else no XVO and anonymous, send public headers below
705 // Send public headers
706 $response->header( $out->getVaryHeader() );
708 $response->header( $out->getXVO() );
711 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
712 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
713 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
715 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
716 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
719 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
720 // Public cache not requested
721 // Sending a Vary header in this case is harmless, and protects us
722 // against conditional calls of setCacheMaxAge().
723 $response->header( "Cache-Control: $privateCache" );
728 $this->mCacheControl
['public'] = true;
730 // Send an Expires header
731 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
732 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
733 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
735 // Construct the Cache-Control header
738 foreach ( $this->mCacheControl
as $name => $value ) {
739 if ( is_bool( $value ) ) {
741 $ccHeader .= $separator . $name;
745 $ccHeader .= $separator . "$name=$value";
750 $response->header( "Cache-Control: $ccHeader" );
754 * Replace the result data with the information about an exception.
755 * Returns the error code
756 * @param Exception $e
759 protected function substituteResultWithError( $e ) {
760 $result = $this->getResult();
762 // Printer may not be initialized if the extractRequestParams() fails for the main module
763 if ( !isset( $this->mPrinter
) ) {
764 // The printer has not been created yet. Try to manually get formatter value.
765 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
766 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
767 $value = self
::API_DEFAULT_FORMAT
;
770 $this->mPrinter
= $this->createPrinterByName( $value );
773 // Printer may not be able to handle errors. This is particularly
774 // likely if the module returns something for getCustomPrinter().
775 if ( !$this->mPrinter
->canPrintErrors() ) {
776 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
779 // Update raw mode flag for the selected printer.
780 $result->setRawMode( $this->mPrinter
->getNeedsRawData() );
782 $config = $this->getConfig();
784 if ( $e instanceof UsageException
) {
785 // User entered incorrect parameters - generate error response
786 $errMessage = $e->getMessageArray();
787 $link = wfExpandUrl( wfScript( 'api' ) );
788 ApiResult
::setContent( $errMessage, "See $link for API usage" );
790 // Something is seriously wrong
791 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
792 $info = 'Database query error';
794 $info = "Exception Caught: {$e->getMessage()}";
798 'code' => 'internal_api_error_' . get_class( $e ),
799 'info' => '[' . MWExceptionHandler
::getLogId( $e ) . '] ' . $info,
801 if ( $config->get( 'ShowExceptionDetails' ) ) {
802 ApiResult
::setContent(
804 MWExceptionHandler
::getRedactedTraceAsString( $e )
809 // Remember all the warnings to re-add them later
810 $oldResult = $result->getData();
811 $warnings = isset( $oldResult['warnings'] ) ?
$oldResult['warnings'] : null;
815 $requestid = $this->getParameter( 'requestid' );
816 if ( !is_null( $requestid ) ) {
817 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
819 if ( $config->get( 'ShowHostnames' ) ) {
820 // servedby is especially useful when debugging errors
821 $result->addValue( null, 'servedby', wfHostName(), ApiResult
::NO_SIZE_CHECK
);
823 if ( $warnings !== null ) {
824 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
827 $result->addValue( null, 'error', $errMessage, ApiResult
::NO_SIZE_CHECK
);
829 return $errMessage['code'];
833 * Set up for the execution.
836 protected function setupExecuteAction() {
837 // First add the id to the top element
838 $result = $this->getResult();
839 $requestid = $this->getParameter( 'requestid' );
840 if ( !is_null( $requestid ) ) {
841 $result->addValue( null, 'requestid', $requestid );
844 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
845 $servedby = $this->getParameter( 'servedby' );
847 $result->addValue( null, 'servedby', wfHostName() );
851 if ( $this->getParameter( 'curtimestamp' ) ) {
852 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
853 ApiResult
::NO_SIZE_CHECK
);
856 $params = $this->extractRequestParams();
858 $this->mAction
= $params['action'];
860 if ( !is_string( $this->mAction
) ) {
861 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
868 * Set up the module for response
869 * @return ApiBase The module that will handle this action
870 * @throws MWException
871 * @throws UsageException
873 protected function setupModule() {
874 // Instantiate the module requested by the user
875 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
876 if ( $module === null ) {
877 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
879 $moduleParams = $module->extractRequestParams();
881 // Check token, if necessary
882 if ( $module->needsToken() === true ) {
883 throw new MWException(
884 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
885 "See documentation for ApiBase::needsToken for details."
888 if ( $module->needsToken() ) {
889 if ( !$module->mustBePosted() ) {
890 throw new MWException(
891 "Module '{$module->getModuleName()}' must require POST to use tokens."
895 if ( !isset( $moduleParams['token'] ) ) {
896 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
899 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
901 $module->encodeParamName( 'token' ),
902 $this->getRequest()->getQueryValues()
906 "The '{$module->encodeParamName( 'token' )}' parameter was found in the query string, but must be in the POST body",
911 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
912 $this->dieUsageMsg( 'sessionfailure' );
920 * Check the max lag if necessary
921 * @param ApiBase $module Api module being used
922 * @param array $params Array an array containing the request parameters.
923 * @return bool True on success, false should exit immediately
925 protected function checkMaxLag( $module, $params ) {
926 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
928 $maxLag = $params['maxlag'];
929 list( $host, $lag ) = wfGetLB()->getMaxLag();
930 if ( $lag > $maxLag ) {
931 $response = $this->getRequest()->response();
933 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
934 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
936 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
937 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
940 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
948 * Check for sufficient permissions to execute
949 * @param ApiBase $module An Api module
951 protected function checkExecutePermissions( $module ) {
952 $user = $this->getUser();
953 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
954 !$user->isAllowed( 'read' )
956 $this->dieUsageMsg( 'readrequired' );
958 if ( $module->isWriteMode() ) {
959 if ( !$this->mEnableWrite
) {
960 $this->dieUsageMsg( 'writedisabled' );
962 if ( !$user->isAllowed( 'writeapi' ) ) {
963 $this->dieUsageMsg( 'writerequired' );
965 if ( wfReadOnly() ) {
966 $this->dieReadOnly();
970 // Allow extensions to stop execution for arbitrary reasons.
972 if ( !Hooks
::run( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
973 $this->dieUsageMsg( $message );
978 * Check asserts of the user's rights
979 * @param array $params
981 protected function checkAsserts( $params ) {
982 if ( isset( $params['assert'] ) ) {
983 $user = $this->getUser();
984 switch ( $params['assert'] ) {
986 if ( $user->isAnon() ) {
987 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
991 if ( !$user->isAllowed( 'bot' ) ) {
992 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1000 * Check POST for external response and setup result printer
1001 * @param ApiBase $module An Api module
1002 * @param array $params An array with the request parameters
1004 protected function setupExternalResponse( $module, $params ) {
1005 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
1006 // Module requires POST. GET request might still be allowed
1007 // if $wgDebugApi is true, otherwise fail.
1008 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction
) );
1011 // See if custom printer is used
1012 $this->mPrinter
= $module->getCustomPrinter();
1013 if ( is_null( $this->mPrinter
) ) {
1014 // Create an appropriate printer
1015 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1018 if ( $this->mPrinter
->getNeedsRawData() ) {
1019 $this->getResult()->setRawMode();
1024 * Execute the actual module, without any error handling
1026 protected function executeAction() {
1027 $params = $this->setupExecuteAction();
1028 $module = $this->setupModule();
1029 $this->mModule
= $module;
1031 $this->checkExecutePermissions( $module );
1033 if ( !$this->checkMaxLag( $module, $params ) ) {
1037 if ( !$this->mInternalMode
) {
1038 $this->setupExternalResponse( $module, $params );
1041 $this->checkAsserts( $params );
1045 Hooks
::run( 'APIAfterExecute', array( &$module ) );
1047 $this->reportUnusedParams();
1049 if ( !$this->mInternalMode
) {
1050 //append Debug information
1051 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1053 // Print result data
1054 $this->printResult( false );
1059 * Log the preceding request
1060 * @param int $time Time in seconds
1062 protected function logRequest( $time ) {
1063 $request = $this->getRequest();
1064 $milliseconds = $time === null ?
'?' : round( $time * 1000 );
1066 ' ' . $request->getMethod() .
1067 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1068 ' ' . $request->getIP() .
1069 ' T=' . $milliseconds . 'ms';
1070 foreach ( $this->getParamsUsed() as $name ) {
1071 $value = $request->getVal( $name );
1072 if ( $value === null ) {
1075 $s .= ' ' . $name . '=';
1076 if ( strlen( $value ) > 256 ) {
1077 $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
1078 $s .= $encValue . '[...]';
1080 $s .= $this->encodeRequestLogValue( $value );
1084 wfDebugLog( 'api', $s, 'private' );
1088 * Encode a value in a format suitable for a space-separated log line.
1092 protected function encodeRequestLogValue( $s ) {
1095 $chars = ';@$!*(),/:';
1096 $numChars = strlen( $chars );
1097 for ( $i = 0; $i < $numChars; $i++
) {
1098 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1102 return strtr( rawurlencode( $s ), $table );
1106 * Get the request parameters used in the course of the preceding execute() request
1109 protected function getParamsUsed() {
1110 return array_keys( $this->mParamsUsed
);
1114 * Get a request value, and register the fact that it was used, for logging.
1115 * @param string $name
1116 * @param mixed $default
1119 public function getVal( $name, $default = null ) {
1120 $this->mParamsUsed
[$name] = true;
1122 $ret = $this->getRequest()->getVal( $name );
1123 if ( $ret === null ) {
1124 if ( $this->getRequest()->getArray( $name ) !== null ) {
1125 // See bug 10262 for why we don't just join( '|', ... ) the
1128 "Parameter '$name' uses unsupported PHP array syntax"
1137 * Get a boolean request value, and register the fact that the parameter
1138 * was used, for logging.
1139 * @param string $name
1142 public function getCheck( $name ) {
1143 return $this->getVal( $name, null ) !== null;
1147 * Get a request upload, and register the fact that it was used, for logging.
1150 * @param string $name Parameter name
1151 * @return WebRequestUpload
1153 public function getUpload( $name ) {
1154 $this->mParamsUsed
[$name] = true;
1156 return $this->getRequest()->getUpload( $name );
1160 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1161 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1163 protected function reportUnusedParams() {
1164 $paramsUsed = $this->getParamsUsed();
1165 $allParams = $this->getRequest()->getValueNames();
1167 if ( !$this->mInternalMode
) {
1168 // Printer has not yet executed; don't warn that its parameters are unused
1169 $printerParams = array_map(
1170 array( $this->mPrinter
, 'encodeParamName' ),
1171 array_keys( $this->mPrinter
->getFinalParams() ?
: array() )
1173 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1175 $unusedParams = array_diff( $allParams, $paramsUsed );
1178 if ( count( $unusedParams ) ) {
1179 $s = count( $unusedParams ) > 1 ?
's' : '';
1180 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1185 * Print results using the current printer
1187 * @param bool $isError
1189 protected function printResult( $isError ) {
1190 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1191 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1194 $this->getResult()->cleanUpUTF8();
1195 $printer = $this->mPrinter
;
1197 $printer->initPrinter( false );
1198 $printer->execute();
1199 $printer->closePrinter();
1205 public function isReadMode() {
1210 * See ApiBase for description.
1214 public function getAllowedParams() {
1217 ApiBase
::PARAM_DFLT
=> 'help',
1218 ApiBase
::PARAM_TYPE
=> 'submodule',
1221 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1222 ApiBase
::PARAM_TYPE
=> 'submodule',
1225 ApiBase
::PARAM_TYPE
=> 'integer'
1228 ApiBase
::PARAM_TYPE
=> 'integer',
1229 ApiBase
::PARAM_DFLT
=> 0
1232 ApiBase
::PARAM_TYPE
=> 'integer',
1233 ApiBase
::PARAM_DFLT
=> 0
1236 ApiBase
::PARAM_TYPE
=> array( 'user', 'bot' )
1238 'requestid' => null,
1239 'servedby' => false,
1240 'curtimestamp' => false,
1243 ApiBase
::PARAM_DFLT
=> 'user',
1248 /** @see ApiBase::getExamplesMessages() */
1249 protected function getExamplesMessages() {
1252 => 'apihelp-help-example-main',
1253 'action=help&recursivesubmodules=1'
1254 => 'apihelp-help-example-recursive',
1258 public function modifyHelp( array &$help, array $options ) {
1259 // Wish PHP had an "array_insert_before". Instead, we have to manually
1260 // reindex the array to get 'permissions' in the right place.
1263 foreach ( $oldHelp as $k => $v ) {
1264 if ( $k === 'submodules' ) {
1265 $help['permissions'] = '';
1269 $help['credits'] = '';
1271 // Fill 'permissions'
1272 $help['permissions'] .= Html
::openElement( 'div',
1273 array( 'class' => 'apihelp-block apihelp-permissions' ) );
1274 $m = $this->msg( 'api-help-permissions' );
1275 if ( !$m->isDisabled() ) {
1276 $help['permissions'] .= Html
::rawElement( 'div', array( 'class' => 'apihelp-block-head' ),
1277 $m->numParams( count( self
::$mRights ) )->parse()
1280 $help['permissions'] .= Html
::openElement( 'dl' );
1281 foreach ( self
::$mRights as $right => $rightMsg ) {
1282 $help['permissions'] .= Html
::element( 'dt', null, $right );
1284 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1285 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1287 $groups = array_map( function ( $group ) {
1288 return $group == '*' ?
'all' : $group;
1289 }, User
::getGroupsWithPermission( $right ) );
1291 $help['permissions'] .= Html
::rawElement( 'dd', null,
1292 $this->msg( 'api-help-permissions-granted-to' )
1293 ->numParams( count( $groups ) )
1294 ->params( $this->getLanguage()->commaList( $groups ) )
1298 $help['permissions'] .= Html
::closeElement( 'dl' );
1299 $help['permissions'] .= Html
::closeElement( 'div' );
1301 // Fill 'credits', if applicable
1302 if ( empty( $options['nolead'] ) ) {
1303 $help['credits'] .= Html
::element( 'h' . min( 6, $options['headerlevel'] +
1 ),
1304 array( 'id' => '+credits', 'class' => 'apihelp-header' ),
1305 $this->msg( 'api-credits-header' )->parse()
1307 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1311 private $mCanApiHighLimits = null;
1314 * Check whether the current user is allowed to use high limits
1317 public function canApiHighLimits() {
1318 if ( !isset( $this->mCanApiHighLimits
) ) {
1319 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1322 return $this->mCanApiHighLimits
;
1326 * Overrides to return this instance's module manager.
1327 * @return ApiModuleManager
1329 public function getModuleManager() {
1330 return $this->mModuleMgr
;
1334 * Fetches the user agent used for this request
1336 * The value will be the combination of the 'Api-User-Agent' header (if
1337 * any) and the standard User-Agent header (if any).
1341 public function getUserAgent() {
1343 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1344 $this->getRequest()->getHeader( 'User-agent' )
1348 /************************************************************************//**
1354 * Sets whether the pretty-printer should format *bold* and $italics$
1356 * @deprecated since 1.25
1359 public function setHelp( $help = true ) {
1360 wfDeprecated( __METHOD__
, '1.25' );
1361 $this->mPrinter
->setHelp( $help );
1365 * Override the parent to generate help messages for all available modules.
1367 * @deprecated since 1.25
1370 public function makeHelpMsg() {
1371 wfDeprecated( __METHOD__
, '1.25' );
1374 // Get help text from cache if present
1375 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1376 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) ) );
1378 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1379 if ( $cacheHelpTimeout > 0 ) {
1380 $cached = $wgMemc->get( $key );
1385 $retval = $this->reallyMakeHelpMsg();
1386 if ( $cacheHelpTimeout > 0 ) {
1387 $wgMemc->set( $key, $retval, $cacheHelpTimeout );
1394 * @deprecated since 1.25
1395 * @return mixed|string
1397 public function reallyMakeHelpMsg() {
1398 wfDeprecated( __METHOD__
, '1.25' );
1401 // Use parent to make default message for the main module
1402 $msg = parent
::makeHelpMsg();
1404 $astriks = str_repeat( '*** ', 14 );
1405 $msg .= "\n\n$astriks Modules $astriks\n\n";
1407 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1408 $module = $this->mModuleMgr
->getModule( $name );
1409 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1411 $msg2 = $module->makeHelpMsg();
1412 if ( $msg2 !== false ) {
1418 $msg .= "\n$astriks Permissions $astriks\n\n";
1419 foreach ( self
::$mRights as $right => $rightMsg ) {
1420 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1421 ->useDatabase( false )
1422 ->inLanguage( 'en' )
1424 $groups = User
::getGroupsWithPermission( $right );
1425 $msg .= "* " . $right . " *\n $rightsMsg" .
1426 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1429 $msg .= "\n$astriks Formats $astriks\n\n";
1430 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1431 $module = $this->mModuleMgr
->getModule( $name );
1432 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1433 $msg2 = $module->makeHelpMsg();
1434 if ( $msg2 !== false ) {
1440 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1441 $credits = str_replace( "\n", "\n ", $credits );
1442 $msg .= "\n*** Credits: ***\n $credits\n";
1448 * @deprecated since 1.25
1449 * @param ApiBase $module
1450 * @param string $paramName What type of request is this? e.g. action,
1451 * query, list, prop, meta, format
1454 public static function makeHelpMsgHeader( $module, $paramName ) {
1455 wfDeprecated( __METHOD__
, '1.25' );
1456 $modulePrefix = $module->getModulePrefix();
1457 if ( strval( $modulePrefix ) !== '' ) {
1458 $modulePrefix = "($modulePrefix) ";
1461 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1465 * Check whether the user wants us to show version information in the API help
1467 * @deprecated since 1.21, always returns false
1469 public function getShowVersions() {
1470 wfDeprecated( __METHOD__
, '1.21' );
1476 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1477 * classes who wish to add their own modules to their lexicon or override the
1478 * behavior of inherent ones.
1480 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1481 * @param string $name The identifier for this module.
1482 * @param ApiBase $class The class where this module is implemented.
1484 protected function addModule( $name, $class ) {
1485 $this->getModuleManager()->addModule( $name, 'action', $class );
1489 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1490 * classes who wish to add to or modify current formatters.
1492 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1493 * @param string $name The identifier for this format.
1494 * @param ApiFormatBase $class The class implementing this format.
1496 protected function addFormat( $name, $class ) {
1497 $this->getModuleManager()->addModule( $name, 'format', $class );
1501 * Get the array mapping module names to class names
1502 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1505 function getModules() {
1506 return $this->getModuleManager()->getNamesWithClasses( 'action' );
1510 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1513 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1516 public function getFormats() {
1517 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1525 * This exception will be thrown when dieUsage is called to stop module execution.
1529 class UsageException
extends MWException
{
1536 private $mExtraData;
1539 * @param string $message
1540 * @param string $codestr
1542 * @param array|null $extradata
1544 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1545 parent
::__construct( $message, $code );
1546 $this->mCodestr
= $codestr;
1547 $this->mExtraData
= $extradata;
1553 public function getCodeString() {
1554 return $this->mCodestr
;
1560 public function getMessageArray() {
1562 'code' => $this->mCodestr
,
1563 'info' => $this->getMessage()
1565 if ( is_array( $this->mExtraData
) ) {
1566 $result = array_merge( $result, $this->mExtraData
);
1575 public function __toString() {
1576 return "{$this->getCodeString()}: {$this->getMessage()}";
1581 * For really cool vim folding this needs to be at the end:
1582 * vim: foldmarker=@{,@} foldmethod=marker