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 'opensearch' => 'ApiOpenSearch',
58 'feedcontributions' => 'ApiFeedContributions',
59 'feedrecentchanges' => 'ApiFeedRecentChanges',
60 'feedwatchlist' => 'ApiFeedWatchlist',
62 'paraminfo' => 'ApiParamInfo',
64 'compare' => 'ApiComparePages',
65 'tokens' => 'ApiTokens',
68 'purge' => 'ApiPurge',
69 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
70 'rollback' => 'ApiRollback',
71 'delete' => 'ApiDelete',
72 'undelete' => 'ApiUndelete',
73 'protect' => 'ApiProtect',
74 'block' => 'ApiBlock',
75 'unblock' => 'ApiUnblock',
77 'edit' => 'ApiEditPage',
78 'upload' => 'ApiUpload',
79 'filerevert' => 'ApiFileRevert',
80 'emailuser' => 'ApiEmailUser',
81 'watch' => 'ApiWatch',
82 'patrol' => 'ApiPatrol',
83 'import' => 'ApiImport',
84 'clearhasmsg' => 'ApiClearHasMsg',
85 'userrights' => 'ApiUserrights',
86 'options' => 'ApiOptions',
87 'imagerotate' => 'ApiImageRotate',
88 'revisiondelete' => 'ApiRevisionDelete',
92 * List of available formats: format name => format class
94 private static $Formats = array(
95 'json' => 'ApiFormatJson',
96 'jsonfm' => 'ApiFormatJson',
97 'php' => 'ApiFormatPhp',
98 'phpfm' => 'ApiFormatPhp',
99 'wddx' => 'ApiFormatWddx',
100 'wddxfm' => 'ApiFormatWddx',
101 'xml' => 'ApiFormatXml',
102 'xmlfm' => 'ApiFormatXml',
103 'yaml' => 'ApiFormatYaml',
104 'yamlfm' => 'ApiFormatYaml',
105 'rawfm' => 'ApiFormatJson',
106 'txt' => 'ApiFormatTxt',
107 'txtfm' => 'ApiFormatTxt',
108 'dbg' => 'ApiFormatDbg',
109 'dbgfm' => 'ApiFormatDbg',
110 'dump' => 'ApiFormatDump',
111 'dumpfm' => 'ApiFormatDump',
112 'none' => 'ApiFormatNone',
115 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
117 * List of user roles that are specifically relevant to the API.
118 * array( 'right' => array ( 'msg' => 'Some message with a $1',
119 * 'params' => array ( $someVarToSubst ) ),
122 private static $mRights = array(
124 'msg' => 'right-writeapi',
127 'apihighlimits' => array(
128 'msg' => 'api-help-right-apihighlimits',
129 'params' => array( ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
)
132 // @codingStandardsIgnoreEnd
139 private $mModuleMgr, $mResult;
141 private $mEnableWrite;
142 private $mInternalMode, $mSquidMaxage, $mModule;
144 private $mCacheMode = 'private';
145 private $mCacheControl = array();
146 private $mParamsUsed = array();
149 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
151 * @param IContextSource|WebRequest $context If this is an instance of
152 * FauxRequest, errors are thrown and no printing occurs
153 * @param bool $enableWrite Should be set to true if the api may modify data
155 public function __construct( $context = null, $enableWrite = false ) {
156 if ( $context === null ) {
157 $context = RequestContext
::getMain();
158 } elseif ( $context instanceof WebRequest
) {
161 $context = RequestContext
::getMain();
163 // We set a derivative context so we can change stuff later
164 $this->setContext( new DerivativeContext( $context ) );
166 if ( isset( $request ) ) {
167 $this->getContext()->setRequest( $request );
170 $this->mInternalMode
= ( $this->getRequest() instanceof FauxRequest
);
172 // Special handling for the main module: $parent === $this
173 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
175 if ( !$this->mInternalMode
) {
176 // Impose module restrictions.
177 // If the current user cannot read,
178 // Remove all modules other than login
181 if ( $this->getVal( 'callback' ) !== null ) {
182 // JSON callback allows cross-site reads.
183 // For safety, strip user credentials.
184 wfDebug( "API: stripping user credentials for JSON callback\n" );
185 $wgUser = new User();
186 $this->getContext()->setUser( $wgUser );
190 $uselang = $this->getParameter( 'uselang' );
191 if ( $uselang === 'user' ) {
192 $uselang = $this->getUser()->getOption( 'language' );
193 $uselang = RequestContext
::sanitizeLangCode( $uselang );
194 wfRunHooks( 'UserGetLanguageObject', array( $this->getUser(), &$uselang, $this ) );
195 } elseif ( $uselang === 'content' ) {
197 $uselang = $wgContLang->getCode();
199 $code = RequestContext
::sanitizeLangCode( $uselang );
200 $this->getContext()->setLanguage( $code );
201 if ( !$this->mInternalMode
) {
203 $wgLang = $this->getContext()->getLanguage();
204 RequestContext
::getMain()->setLanguage( $wgLang );
207 $config = $this->getConfig();
208 $this->mModuleMgr
= new ApiModuleManager( $this );
209 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
210 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
211 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
212 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
214 $this->mResult
= new ApiResult( $this );
215 $this->mEnableWrite
= $enableWrite;
217 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
218 $this->mCommit
= false;
222 * Return true if the API was started by other PHP code using FauxRequest
225 public function isInternalMode() {
226 return $this->mInternalMode
;
230 * Get the ApiResult object associated with current request
234 public function getResult() {
235 return $this->mResult
;
239 * Get the API module object. Only works after executeAction()
243 public function getModule() {
244 return $this->mModule
;
248 * Get the result formatter object. Only works after setupExecuteAction()
250 * @return ApiFormatBase
252 public function getPrinter() {
253 return $this->mPrinter
;
257 * Set how long the response should be cached.
261 public function setCacheMaxAge( $maxage ) {
262 $this->setCacheControl( array(
263 'max-age' => $maxage,
264 's-maxage' => $maxage
269 * Set the type of caching headers which will be sent.
271 * @param string $mode One of:
272 * - 'public': Cache this object in public caches, if the maxage or smaxage
273 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
274 * not provided by any of these means, the object will be private.
275 * - 'private': Cache this object only in private client-side caches.
276 * - 'anon-public-user-private': Make this object cacheable for logged-out
277 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
278 * set consistently for a given URL, it cannot be set differently depending on
279 * things like the contents of the database, or whether the user is logged in.
281 * If the wiki does not allow anonymous users to read it, the mode set here
282 * will be ignored, and private caching headers will always be sent. In other words,
283 * the "public" mode is equivalent to saying that the data sent is as public as a page
286 * For user-dependent data, the private mode should generally be used. The
287 * anon-public-user-private mode should only be used where there is a particularly
288 * good performance reason for caching the anonymous response, but where the
289 * response to logged-in users may differ, or may contain private data.
291 * If this function is never called, then the default will be the private mode.
293 public function setCacheMode( $mode ) {
294 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
295 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
297 // Ignore for forwards-compatibility
301 if ( !User
::isEveryoneAllowed( 'read' ) ) {
302 // Private wiki, only private headers
303 if ( $mode !== 'private' ) {
304 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
310 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
311 // User language is used for i18n, so we don't want to publicly
312 // cache. Anons are ok, because if they have non-default language
313 // then there's an appropriate Vary header set by whatever set
314 // their non-default language.
315 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
316 "'anon-public-user-private' due to uselang=user\n" );
317 $mode = 'anon-public-user-private';
320 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
321 $this->mCacheMode
= $mode;
325 * Set directives (key/value pairs) for the Cache-Control header.
326 * Boolean values will be formatted as such, by including or omitting
327 * without an equals sign.
329 * Cache control values set here will only be used if the cache mode is not
330 * private, see setCacheMode().
332 * @param array $directives
334 public function setCacheControl( $directives ) {
335 $this->mCacheControl
= $directives +
$this->mCacheControl
;
339 * Create an instance of an output formatter by its name
341 * @param string $format
343 * @return ApiFormatBase
345 public function createPrinterByName( $format ) {
346 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
347 if ( $printer === null ) {
348 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
355 * Execute api request. Any errors will be handled if the API was called by the remote client.
357 public function execute() {
359 if ( $this->mInternalMode
) {
360 $this->executeAction();
362 $this->executeActionWithErrorHandling();
369 * Execute an action, and in case of an error, erase whatever partial results
370 * have been accumulated, and replace it with an error message and a help screen.
372 protected function executeActionWithErrorHandling() {
373 // Verify the CORS header before executing the action
374 if ( !$this->handleCORS() ) {
375 // handleCORS() has sent a 403, abort
379 // Exit here if the request method was OPTIONS
380 // (assume there will be a followup GET or POST)
381 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
385 // In case an error occurs during data output,
386 // clear the output buffer and print just the error information
389 $t = microtime( true );
391 $this->executeAction();
392 } catch ( Exception
$e ) {
393 $this->handleException( $e );
396 // Log the request whether or not there was an error
397 $this->logRequest( microtime( true ) - $t );
399 // Send cache headers after any code which might generate an error, to
400 // avoid sending public cache headers for errors.
401 $this->sendCacheHeaders();
407 * Handle an exception as an API response
410 * @param Exception $e
412 protected function handleException( Exception
$e ) {
413 // Bug 63145: Rollback any open database transactions
414 if ( !( $e instanceof UsageException
) ) {
415 // UsageExceptions are intentional, so don't rollback if that's the case
416 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
419 // Allow extra cleanup and logging
420 wfRunHooks( 'ApiMain::onException', array( $this, $e ) );
423 if ( !( $e instanceof UsageException
) ) {
424 MWExceptionHandler
::logException( $e );
427 // Handle any kind of exception by outputting properly formatted error message.
428 // If this fails, an unhandled exception should be thrown so that global error
429 // handler will process and log it.
431 $errCode = $this->substituteResultWithError( $e );
433 // Error results should not be cached
434 $this->setCacheMode( 'private' );
436 $response = $this->getRequest()->response();
437 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
438 if ( $e->getCode() === 0 ) {
439 $response->header( $headerStr );
441 $response->header( $headerStr, true, $e->getCode() );
444 // Reset and print just the error message
447 // If the error occurred during printing, do a printer->profileOut()
448 $this->mPrinter
->safeProfileOut();
449 $this->printResult( true );
453 * Handle an exception from the ApiBeforeMain hook.
455 * This tries to print the exception as an API response, to be more
456 * friendly to clients. If it fails, it will rethrow the exception.
459 * @param Exception $e
461 public static function handleApiBeforeMainException( Exception
$e ) {
465 $main = new self( RequestContext
::getMain(), false );
466 $main->handleException( $e );
467 } catch ( Exception
$e2 ) {
468 // Nope, even that didn't work. Punt.
472 // Log the request and reset cache headers
473 $main->logRequest( 0 );
474 $main->sendCacheHeaders();
480 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
482 * If no origin parameter is present, nothing happens.
483 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
484 * is set and false is returned.
485 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
486 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
489 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
491 protected function handleCORS() {
492 $originParam = $this->getParameter( 'origin' ); // defaults to null
493 if ( $originParam === null ) {
494 // No origin parameter, nothing to do
498 $request = $this->getRequest();
499 $response = $request->response();
500 // Origin: header is a space-separated list of origins, check all of them
501 $originHeader = $request->getHeader( 'Origin' );
502 if ( $originHeader === false ) {
505 $origins = explode( ' ', $originHeader );
508 if ( !in_array( $originParam, $origins ) ) {
509 // origin parameter set but incorrect
510 // Send a 403 response
511 $message = HttpStatus
::getMessage( 403 );
512 $response->header( "HTTP/1.1 403 $message", true, 403 );
513 $response->header( 'Cache-Control: no-cache' );
514 echo "'origin' parameter does not match Origin header\n";
519 $config = $this->getConfig();
520 $matchOrigin = self
::matchOrigin(
522 $config->get( 'CrossSiteAJAXdomains' ),
523 $config->get( 'CrossSiteAJAXdomainExceptions' )
526 if ( $matchOrigin ) {
527 $response->header( "Access-Control-Allow-Origin: $originParam" );
528 $response->header( 'Access-Control-Allow-Credentials: true' );
529 $response->header( 'Access-Control-Allow-Headers: Api-User-Agent' );
530 $this->getOutput()->addVaryHeader( 'Origin' );
537 * Attempt to match an Origin header against a set of rules and a set of exceptions
538 * @param string $value Origin header
539 * @param array $rules Set of wildcard rules
540 * @param array $exceptions Set of wildcard rules
541 * @return bool True if $value matches a rule in $rules and doesn't match
542 * any rules in $exceptions, false otherwise
544 protected static function matchOrigin( $value, $rules, $exceptions ) {
545 foreach ( $rules as $rule ) {
546 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
547 // Rule matches, check exceptions
548 foreach ( $exceptions as $exc ) {
549 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
562 * Helper function to convert wildcard string into a regex
566 * @param string $wildcard String with wildcards
567 * @return string Regular expression
569 protected static function wildcardToRegex( $wildcard ) {
570 $wildcard = preg_quote( $wildcard, '/' );
571 $wildcard = str_replace(
577 return "/https?:\/\/$wildcard/";
580 protected function sendCacheHeaders() {
581 $response = $this->getRequest()->response();
582 $out = $this->getOutput();
584 $config = $this->getConfig();
586 if ( $config->get( 'VaryOnXFP' ) ) {
587 $out->addVaryHeader( 'X-Forwarded-Proto' );
590 if ( $this->mCacheMode
== 'private' ) {
591 $response->header( 'Cache-Control: private' );
595 $useXVO = $config->get( 'UseXVO' );
596 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
597 $out->addVaryHeader( 'Cookie' );
598 $response->header( $out->getVaryHeader() );
600 $response->header( $out->getXVO() );
601 if ( $out->haveCacheVaryCookies() ) {
602 // Logged in, mark this request private
603 $response->header( 'Cache-Control: private' );
606 // Logged out, send normal public headers below
607 } elseif ( session_id() != '' ) {
608 // Logged in or otherwise has session (e.g. anonymous users who have edited)
609 // Mark request private
610 $response->header( 'Cache-Control: private' );
613 } // else no XVO and anonymous, send public headers below
616 // Send public headers
617 $response->header( $out->getVaryHeader() );
619 $response->header( $out->getXVO() );
622 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
623 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
624 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
626 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
627 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
630 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
631 // Public cache not requested
632 // Sending a Vary header in this case is harmless, and protects us
633 // against conditional calls of setCacheMaxAge().
634 $response->header( 'Cache-Control: private' );
639 $this->mCacheControl
['public'] = true;
641 // Send an Expires header
642 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
643 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
644 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
646 // Construct the Cache-Control header
649 foreach ( $this->mCacheControl
as $name => $value ) {
650 if ( is_bool( $value ) ) {
652 $ccHeader .= $separator . $name;
656 $ccHeader .= $separator . "$name=$value";
661 $response->header( "Cache-Control: $ccHeader" );
665 * Replace the result data with the information about an exception.
666 * Returns the error code
667 * @param Exception $e
670 protected function substituteResultWithError( $e ) {
671 $result = $this->getResult();
673 // Printer may not be initialized if the extractRequestParams() fails for the main module
674 if ( !isset( $this->mPrinter
) ) {
675 // The printer has not been created yet. Try to manually get formatter value.
676 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
677 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
678 $value = self
::API_DEFAULT_FORMAT
;
681 $this->mPrinter
= $this->createPrinterByName( $value );
684 // Printer may not be able to handle errors. This is particularly
685 // likely if the module returns something for getCustomPrinter().
686 if ( !$this->mPrinter
->canPrintErrors() ) {
687 $this->mPrinter
->safeProfileOut();
688 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
691 // Update raw mode flag for the selected printer.
692 $result->setRawMode( $this->mPrinter
->getNeedsRawData() );
694 $config = $this->getConfig();
696 if ( $e instanceof UsageException
) {
697 // User entered incorrect parameters - generate error response
698 $errMessage = $e->getMessageArray();
699 $link = wfExpandUrl( wfScript( 'api' ) );
700 ApiResult
::setContent( $errMessage, "See $link for API usage" );
702 // Something is seriously wrong
703 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
704 $info = 'Database query error';
706 $info = "Exception Caught: {$e->getMessage()}";
710 'code' => 'internal_api_error_' . get_class( $e ),
713 ApiResult
::setContent(
715 $config->get( 'ShowExceptionDetails' ) ?
"\n\n{$e->getTraceAsString()}\n\n" : ''
719 // Remember all the warnings to re-add them later
720 $oldResult = $result->getData();
721 $warnings = isset( $oldResult['warnings'] ) ?
$oldResult['warnings'] : null;
725 $requestid = $this->getParameter( 'requestid' );
726 if ( !is_null( $requestid ) ) {
727 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
729 if ( $config->get( 'ShowHostnames' ) ) {
730 // servedby is especially useful when debugging errors
731 $result->addValue( null, 'servedby', wfHostName(), ApiResult
::NO_SIZE_CHECK
);
733 if ( $warnings !== null ) {
734 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
737 $result->addValue( null, 'error', $errMessage, ApiResult
::NO_SIZE_CHECK
);
739 return $errMessage['code'];
743 * Set up for the execution.
746 protected function setupExecuteAction() {
747 // First add the id to the top element
748 $result = $this->getResult();
749 $requestid = $this->getParameter( 'requestid' );
750 if ( !is_null( $requestid ) ) {
751 $result->addValue( null, 'requestid', $requestid );
754 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
755 $servedby = $this->getParameter( 'servedby' );
757 $result->addValue( null, 'servedby', wfHostName() );
761 if ( $this->getParameter( 'curtimestamp' ) ) {
762 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
763 ApiResult
::NO_SIZE_CHECK
);
766 $params = $this->extractRequestParams();
768 $this->mAction
= $params['action'];
770 if ( !is_string( $this->mAction
) ) {
771 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
778 * Set up the module for response
779 * @return ApiBase The module that will handle this action
781 protected function setupModule() {
782 // Instantiate the module requested by the user
783 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
784 if ( $module === null ) {
785 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
787 $moduleParams = $module->extractRequestParams();
789 // Check token, if necessary
790 if ( $module->needsToken() === true ) {
791 throw new MWException(
792 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
793 "See documentation for ApiBase::needsToken for details."
796 if ( $module->needsToken() ) {
797 if ( !$module->mustBePosted() ) {
798 throw new MWException(
799 "Module '{$module->getModuleName()}' must require POST to use tokens."
803 if ( !isset( $moduleParams['token'] ) ) {
804 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
807 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
809 $module->encodeParamName( 'token' ),
810 $this->getRequest()->getQueryValues()
814 "The '{$module->encodeParamName( 'token' )}' parameter was found in the query string, but must be in the POST body",
819 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
820 $this->dieUsageMsg( 'sessionfailure' );
828 * Check the max lag if necessary
829 * @param ApiBase $module Api module being used
830 * @param array $params Array an array containing the request parameters.
831 * @return bool True on success, false should exit immediately
833 protected function checkMaxLag( $module, $params ) {
834 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
836 $maxLag = $params['maxlag'];
837 list( $host, $lag ) = wfGetLB()->getMaxLag();
838 if ( $lag > $maxLag ) {
839 $response = $this->getRequest()->response();
841 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
842 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
844 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
845 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
848 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
856 * Check for sufficient permissions to execute
857 * @param ApiBase $module An Api module
859 protected function checkExecutePermissions( $module ) {
860 $user = $this->getUser();
861 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
862 !$user->isAllowed( 'read' )
864 $this->dieUsageMsg( 'readrequired' );
866 if ( $module->isWriteMode() ) {
867 if ( !$this->mEnableWrite
) {
868 $this->dieUsageMsg( 'writedisabled' );
870 if ( !$user->isAllowed( 'writeapi' ) ) {
871 $this->dieUsageMsg( 'writerequired' );
873 if ( wfReadOnly() ) {
874 $this->dieReadOnly();
878 // Allow extensions to stop execution for arbitrary reasons.
880 if ( !wfRunHooks( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
881 $this->dieUsageMsg( $message );
886 * Check asserts of the user's rights
887 * @param array $params
889 protected function checkAsserts( $params ) {
890 if ( isset( $params['assert'] ) ) {
891 $user = $this->getUser();
892 switch ( $params['assert'] ) {
894 if ( $user->isAnon() ) {
895 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
899 if ( !$user->isAllowed( 'bot' ) ) {
900 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
908 * Check POST for external response and setup result printer
909 * @param ApiBase $module An Api module
910 * @param array $params An array with the request parameters
912 protected function setupExternalResponse( $module, $params ) {
913 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
914 // Module requires POST. GET request might still be allowed
915 // if $wgDebugApi is true, otherwise fail.
916 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction
) );
919 // See if custom printer is used
920 $this->mPrinter
= $module->getCustomPrinter();
921 if ( is_null( $this->mPrinter
) ) {
922 // Create an appropriate printer
923 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
926 if ( $this->mPrinter
->getNeedsRawData() ) {
927 $this->getResult()->setRawMode();
932 * Execute the actual module, without any error handling
934 protected function executeAction() {
935 $params = $this->setupExecuteAction();
936 $module = $this->setupModule();
937 $this->mModule
= $module;
939 $this->checkExecutePermissions( $module );
941 if ( !$this->checkMaxLag( $module, $params ) ) {
945 if ( !$this->mInternalMode
) {
946 $this->setupExternalResponse( $module, $params );
949 $this->checkAsserts( $params );
952 $module->profileIn();
954 wfRunHooks( 'APIAfterExecute', array( &$module ) );
955 $module->profileOut();
957 $this->reportUnusedParams();
959 if ( !$this->mInternalMode
) {
960 //append Debug information
961 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
964 $this->printResult( false );
969 * Log the preceding request
970 * @param int $time Time in seconds
972 protected function logRequest( $time ) {
973 $request = $this->getRequest();
974 $milliseconds = $time === null ?
'?' : round( $time * 1000 );
976 ' ' . $request->getMethod() .
977 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
978 ' ' . $request->getIP() .
979 ' T=' . $milliseconds . 'ms';
980 foreach ( $this->getParamsUsed() as $name ) {
981 $value = $request->getVal( $name );
982 if ( $value === null ) {
985 $s .= ' ' . $name . '=';
986 if ( strlen( $value ) > 256 ) {
987 $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
988 $s .= $encValue . '[...]';
990 $s .= $this->encodeRequestLogValue( $value );
994 wfDebugLog( 'api', $s, 'private' );
998 * Encode a value in a format suitable for a space-separated log line.
1002 protected function encodeRequestLogValue( $s ) {
1005 $chars = ';@$!*(),/:';
1006 $numChars = strlen( $chars );
1007 for ( $i = 0; $i < $numChars; $i++
) {
1008 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1012 return strtr( rawurlencode( $s ), $table );
1016 * Get the request parameters used in the course of the preceding execute() request
1019 protected function getParamsUsed() {
1020 return array_keys( $this->mParamsUsed
);
1024 * Get a request value, and register the fact that it was used, for logging.
1025 * @param string $name
1026 * @param mixed $default
1029 public function getVal( $name, $default = null ) {
1030 $this->mParamsUsed
[$name] = true;
1032 $ret = $this->getRequest()->getVal( $name );
1033 if ( $ret === null ) {
1034 if ( $this->getRequest()->getArray( $name ) !== null ) {
1035 // See bug 10262 for why we don't just join( '|', ... ) the
1038 "Parameter '$name' uses unsupported PHP array syntax"
1047 * Get a boolean request value, and register the fact that the parameter
1048 * was used, for logging.
1049 * @param string $name
1052 public function getCheck( $name ) {
1053 return $this->getVal( $name, null ) !== null;
1057 * Get a request upload, and register the fact that it was used, for logging.
1060 * @param string $name Parameter name
1061 * @return WebRequestUpload
1063 public function getUpload( $name ) {
1064 $this->mParamsUsed
[$name] = true;
1066 return $this->getRequest()->getUpload( $name );
1070 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1071 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1073 protected function reportUnusedParams() {
1074 $paramsUsed = $this->getParamsUsed();
1075 $allParams = $this->getRequest()->getValueNames();
1077 if ( !$this->mInternalMode
) {
1078 // Printer has not yet executed; don't warn that its parameters are unused
1079 $printerParams = array_map(
1080 array( $this->mPrinter
, 'encodeParamName' ),
1081 array_keys( $this->mPrinter
->getFinalParams() ?
: array() )
1083 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1085 $unusedParams = array_diff( $allParams, $paramsUsed );
1088 if ( count( $unusedParams ) ) {
1089 $s = count( $unusedParams ) > 1 ?
's' : '';
1090 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1095 * Print results using the current printer
1097 * @param bool $isError
1099 protected function printResult( $isError ) {
1100 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1101 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1104 $this->getResult()->cleanUpUTF8();
1105 $printer = $this->mPrinter
;
1106 $printer->profileIn();
1108 $printer->initPrinter( false );
1110 $printer->execute();
1111 $printer->closePrinter();
1112 $printer->profileOut();
1118 public function isReadMode() {
1123 * See ApiBase for description.
1127 public function getAllowedParams() {
1130 ApiBase
::PARAM_DFLT
=> 'help',
1131 ApiBase
::PARAM_TYPE
=> 'submodule',
1134 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1135 ApiBase
::PARAM_TYPE
=> 'submodule',
1138 ApiBase
::PARAM_TYPE
=> 'integer'
1141 ApiBase
::PARAM_TYPE
=> 'integer',
1142 ApiBase
::PARAM_DFLT
=> 0
1145 ApiBase
::PARAM_TYPE
=> 'integer',
1146 ApiBase
::PARAM_DFLT
=> 0
1149 ApiBase
::PARAM_TYPE
=> array( 'user', 'bot' )
1151 'requestid' => null,
1152 'servedby' => false,
1153 'curtimestamp' => false,
1156 ApiBase
::PARAM_DFLT
=> 'user',
1161 /** @see ApiBase::getExamplesMessages() */
1162 protected function getExamplesMessages() {
1165 => 'apihelp-help-example-main',
1166 'action=help&recursivesubmodules=1'
1167 => 'apihelp-help-example-recursive',
1171 public function modifyHelp( array &$help, array $options ) {
1172 // Wish PHP had an "array_insert_before". Instead, we have to manually
1173 // reindex the array to get 'permissions' in the right place.
1176 foreach ( $oldHelp as $k => $v ) {
1177 if ( $k === 'submodules' ) {
1178 $help['permissions'] = '';
1182 $help['credits'] = '';
1184 // Fill 'permissions'
1185 $help['permissions'] .= Html
::openElement( 'div',
1186 array( 'class' => 'apihelp-block apihelp-permissions' ) );
1187 $m = $this->msg( 'api-help-permissions' );
1188 if ( !$m->isDisabled() ) {
1189 $help['permissions'] .= Html
::rawElement( 'div', array( 'class' => 'apihelp-block-head' ),
1190 $m->numParams( count( self
::$mRights ) )->parse()
1193 $help['permissions'] .= Html
::openElement( 'dl' );
1194 foreach ( self
::$mRights as $right => $rightMsg ) {
1195 $help['permissions'] .= Html
::element( 'dt', null, $right );
1197 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1198 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1200 $groups = array_map( function ( $group ) {
1201 return $group == '*' ?
'all' : $group;
1202 }, User
::getGroupsWithPermission( $right ) );
1204 $help['permissions'] .= Html
::rawElement( 'dd', null,
1205 $this->msg( 'api-help-permissions-granted-to' )
1206 ->numParams( count( $groups ) )
1207 ->params( $this->getLanguage()->commaList( $groups ) )
1211 $help['permissions'] .= Html
::closeElement( 'dl' );
1212 $help['permissions'] .= Html
::closeElement( 'div' );
1214 // Fill 'credits', if applicable
1215 if ( empty( $options['nolead'] ) ) {
1216 $help['credits'] .= Html
::element( 'h' . min( 6, $options['headerlevel'] +
1 ),
1217 array( 'id' => '+credits', 'class' => 'apihelp-header' ),
1218 $this->msg( 'api-credits-header' )->parse()
1220 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1224 private $mCanApiHighLimits = null;
1227 * Check whether the current user is allowed to use high limits
1230 public function canApiHighLimits() {
1231 if ( !isset( $this->mCanApiHighLimits
) ) {
1232 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1235 return $this->mCanApiHighLimits
;
1239 * Overrides to return this instance's module manager.
1240 * @return ApiModuleManager
1242 public function getModuleManager() {
1243 return $this->mModuleMgr
;
1247 * Fetches the user agent used for this request
1249 * The value will be the combination of the 'Api-User-Agent' header (if
1250 * any) and the standard User-Agent header (if any).
1254 public function getUserAgent() {
1256 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1257 $this->getRequest()->getHeader( 'User-agent' )
1261 /************************************************************************//**
1267 * Sets whether the pretty-printer should format *bold* and $italics$
1269 * @deprecated since 1.25
1272 public function setHelp( $help = true ) {
1273 wfDeprecated( __METHOD__
, '1.25' );
1274 $this->mPrinter
->setHelp( $help );
1278 * Override the parent to generate help messages for all available modules.
1280 * @deprecated since 1.25
1283 public function makeHelpMsg() {
1284 wfDeprecated( __METHOD__
, '1.25' );
1287 // Get help text from cache if present
1288 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1289 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) ) );
1291 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1292 if ( $cacheHelpTimeout > 0 ) {
1293 $cached = $wgMemc->get( $key );
1298 $retval = $this->reallyMakeHelpMsg();
1299 if ( $cacheHelpTimeout > 0 ) {
1300 $wgMemc->set( $key, $retval, $cacheHelpTimeout );
1307 * @deprecated since 1.25
1308 * @return mixed|string
1310 public function reallyMakeHelpMsg() {
1311 wfDeprecated( __METHOD__
, '1.25' );
1314 // Use parent to make default message for the main module
1315 $msg = parent
::makeHelpMsg();
1317 $astriks = str_repeat( '*** ', 14 );
1318 $msg .= "\n\n$astriks Modules $astriks\n\n";
1320 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1321 $module = $this->mModuleMgr
->getModule( $name );
1322 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1324 $msg2 = $module->makeHelpMsg();
1325 if ( $msg2 !== false ) {
1331 $msg .= "\n$astriks Permissions $astriks\n\n";
1332 foreach ( self
::$mRights as $right => $rightMsg ) {
1333 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1334 ->useDatabase( false )
1335 ->inLanguage( 'en' )
1337 $groups = User
::getGroupsWithPermission( $right );
1338 $msg .= "* " . $right . " *\n $rightsMsg" .
1339 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1342 $msg .= "\n$astriks Formats $astriks\n\n";
1343 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1344 $module = $this->mModuleMgr
->getModule( $name );
1345 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1346 $msg2 = $module->makeHelpMsg();
1347 if ( $msg2 !== false ) {
1353 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1354 $credits = str_replace( "\n", "\n ", $credits );
1355 $msg .= "\n*** Credits: ***\n $credits\n";
1361 * @deprecated since 1.25
1362 * @param ApiBase $module
1363 * @param string $paramName What type of request is this? e.g. action,
1364 * query, list, prop, meta, format
1367 public static function makeHelpMsgHeader( $module, $paramName ) {
1368 wfDeprecated( __METHOD__
, '1.25' );
1369 $modulePrefix = $module->getModulePrefix();
1370 if ( strval( $modulePrefix ) !== '' ) {
1371 $modulePrefix = "($modulePrefix) ";
1374 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1378 * Check whether the user wants us to show version information in the API help
1380 * @deprecated since 1.21, always returns false
1382 public function getShowVersions() {
1383 wfDeprecated( __METHOD__
, '1.21' );
1389 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1390 * classes who wish to add their own modules to their lexicon or override the
1391 * behavior of inherent ones.
1393 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1394 * @param string $name The identifier for this module.
1395 * @param ApiBase $class The class where this module is implemented.
1397 protected function addModule( $name, $class ) {
1398 $this->getModuleManager()->addModule( $name, 'action', $class );
1402 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1403 * classes who wish to add to or modify current formatters.
1405 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1406 * @param string $name The identifier for this format.
1407 * @param ApiFormatBase $class The class implementing this format.
1409 protected function addFormat( $name, $class ) {
1410 $this->getModuleManager()->addModule( $name, 'format', $class );
1414 * Get the array mapping module names to class names
1415 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1418 function getModules() {
1419 return $this->getModuleManager()->getNamesWithClasses( 'action' );
1423 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1426 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1429 public function getFormats() {
1430 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1438 * This exception will be thrown when dieUsage is called to stop module execution.
1442 class UsageException
extends MWException
{
1449 private $mExtraData;
1452 * @param string $message
1453 * @param string $codestr
1455 * @param array|null $extradata
1457 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1458 parent
::__construct( $message, $code );
1459 $this->mCodestr
= $codestr;
1460 $this->mExtraData
= $extradata;
1466 public function getCodeString() {
1467 return $this->mCodestr
;
1473 public function getMessageArray() {
1475 'code' => $this->mCodestr
,
1476 'info' => $this->getMessage()
1478 if ( is_array( $this->mExtraData
) ) {
1479 $result = array_merge( $result, $this->mExtraData
);
1488 public function __toString() {
1489 return "{$this->getCodeString()}: {$this->getMessage()}";
1494 * For really cool vim folding this needs to be at the end:
1495 * vim: foldmarker=@{,@} foldmethod=marker