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 ) );
196 $code = RequestContext
::sanitizeLangCode( $uselang );
197 $this->getContext()->setLanguage( $code );
198 if ( !$this->mInternalMode
) {
200 $wgLang = $this->getContext()->getLanguage();
201 RequestContext
::getMain()->setLanguage( $wgLang );
204 $config = $this->getConfig();
205 $this->mModuleMgr
= new ApiModuleManager( $this );
206 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
207 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
208 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
209 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
211 $this->mResult
= new ApiResult( $this );
212 $this->mEnableWrite
= $enableWrite;
214 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
215 $this->mCommit
= false;
219 * Return true if the API was started by other PHP code using FauxRequest
222 public function isInternalMode() {
223 return $this->mInternalMode
;
227 * Get the ApiResult object associated with current request
231 public function getResult() {
232 return $this->mResult
;
236 * Get the API module object. Only works after executeAction()
240 public function getModule() {
241 return $this->mModule
;
245 * Get the result formatter object. Only works after setupExecuteAction()
247 * @return ApiFormatBase
249 public function getPrinter() {
250 return $this->mPrinter
;
254 * Set how long the response should be cached.
258 public function setCacheMaxAge( $maxage ) {
259 $this->setCacheControl( array(
260 'max-age' => $maxage,
261 's-maxage' => $maxage
266 * Set the type of caching headers which will be sent.
268 * @param string $mode One of:
269 * - 'public': Cache this object in public caches, if the maxage or smaxage
270 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
271 * not provided by any of these means, the object will be private.
272 * - 'private': Cache this object only in private client-side caches.
273 * - 'anon-public-user-private': Make this object cacheable for logged-out
274 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
275 * set consistently for a given URL, it cannot be set differently depending on
276 * things like the contents of the database, or whether the user is logged in.
278 * If the wiki does not allow anonymous users to read it, the mode set here
279 * will be ignored, and private caching headers will always be sent. In other words,
280 * the "public" mode is equivalent to saying that the data sent is as public as a page
283 * For user-dependent data, the private mode should generally be used. The
284 * anon-public-user-private mode should only be used where there is a particularly
285 * good performance reason for caching the anonymous response, but where the
286 * response to logged-in users may differ, or may contain private data.
288 * If this function is never called, then the default will be the private mode.
290 public function setCacheMode( $mode ) {
291 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
292 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
294 // Ignore for forwards-compatibility
298 if ( !User
::isEveryoneAllowed( 'read' ) ) {
299 // Private wiki, only private headers
300 if ( $mode !== 'private' ) {
301 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
307 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
308 // User language is used for i18n, so we don't want to publicly
309 // cache. Anons are ok, because if they have non-default language
310 // then there's an appropriate Vary header set by whatever set
311 // their non-default language.
312 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
313 "'anon-public-user-private' due to uselang=user\n" );
314 $mode = 'anon-public-user-private';
317 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
318 $this->mCacheMode
= $mode;
322 * Set directives (key/value pairs) for the Cache-Control header.
323 * Boolean values will be formatted as such, by including or omitting
324 * without an equals sign.
326 * Cache control values set here will only be used if the cache mode is not
327 * private, see setCacheMode().
329 * @param array $directives
331 public function setCacheControl( $directives ) {
332 $this->mCacheControl
= $directives +
$this->mCacheControl
;
336 * Create an instance of an output formatter by its name
338 * @param string $format
340 * @return ApiFormatBase
342 public function createPrinterByName( $format ) {
343 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
344 if ( $printer === null ) {
345 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
352 * Execute api request. Any errors will be handled if the API was called by the remote client.
354 public function execute() {
356 if ( $this->mInternalMode
) {
357 $this->executeAction();
359 $this->executeActionWithErrorHandling();
366 * Execute an action, and in case of an error, erase whatever partial results
367 * have been accumulated, and replace it with an error message and a help screen.
369 protected function executeActionWithErrorHandling() {
370 // Verify the CORS header before executing the action
371 if ( !$this->handleCORS() ) {
372 // handleCORS() has sent a 403, abort
376 // Exit here if the request method was OPTIONS
377 // (assume there will be a followup GET or POST)
378 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
382 // In case an error occurs during data output,
383 // clear the output buffer and print just the error information
386 $t = microtime( true );
388 $this->executeAction();
389 } catch ( Exception
$e ) {
390 $this->handleException( $e );
393 // Log the request whether or not there was an error
394 $this->logRequest( microtime( true ) - $t );
396 // Send cache headers after any code which might generate an error, to
397 // avoid sending public cache headers for errors.
398 $this->sendCacheHeaders();
404 * Handle an exception as an API response
407 * @param Exception $e
409 protected function handleException( Exception
$e ) {
410 // Bug 63145: Rollback any open database transactions
411 if ( !( $e instanceof UsageException
) ) {
412 // UsageExceptions are intentional, so don't rollback if that's the case
413 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
416 // Allow extra cleanup and logging
417 wfRunHooks( 'ApiMain::onException', array( $this, $e ) );
420 if ( !( $e instanceof UsageException
) ) {
421 MWExceptionHandler
::logException( $e );
424 // Handle any kind of exception by outputting properly formatted error message.
425 // If this fails, an unhandled exception should be thrown so that global error
426 // handler will process and log it.
428 $errCode = $this->substituteResultWithError( $e );
430 // Error results should not be cached
431 $this->setCacheMode( 'private' );
433 $response = $this->getRequest()->response();
434 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
435 if ( $e->getCode() === 0 ) {
436 $response->header( $headerStr );
438 $response->header( $headerStr, true, $e->getCode() );
441 // Reset and print just the error message
444 // If the error occurred during printing, do a printer->profileOut()
445 $this->mPrinter
->safeProfileOut();
446 $this->printResult( true );
450 * Handle an exception from the ApiBeforeMain hook.
452 * This tries to print the exception as an API response, to be more
453 * friendly to clients. If it fails, it will rethrow the exception.
456 * @param Exception $e
458 public static function handleApiBeforeMainException( Exception
$e ) {
462 $main = new self( RequestContext
::getMain(), false );
463 $main->handleException( $e );
464 } catch ( Exception
$e2 ) {
465 // Nope, even that didn't work. Punt.
469 // Log the request and reset cache headers
470 $main->logRequest( 0 );
471 $main->sendCacheHeaders();
477 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
479 * If no origin parameter is present, nothing happens.
480 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
481 * is set and false is returned.
482 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
483 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
486 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
488 protected function handleCORS() {
489 $originParam = $this->getParameter( 'origin' ); // defaults to null
490 if ( $originParam === null ) {
491 // No origin parameter, nothing to do
495 $request = $this->getRequest();
496 $response = $request->response();
497 // Origin: header is a space-separated list of origins, check all of them
498 $originHeader = $request->getHeader( 'Origin' );
499 if ( $originHeader === false ) {
502 $origins = explode( ' ', $originHeader );
505 if ( !in_array( $originParam, $origins ) ) {
506 // origin parameter set but incorrect
507 // Send a 403 response
508 $message = HttpStatus
::getMessage( 403 );
509 $response->header( "HTTP/1.1 403 $message", true, 403 );
510 $response->header( 'Cache-Control: no-cache' );
511 echo "'origin' parameter does not match Origin header\n";
516 $config = $this->getConfig();
517 $matchOrigin = self
::matchOrigin(
519 $config->get( 'CrossSiteAJAXdomains' ),
520 $config->get( 'CrossSiteAJAXdomainExceptions' )
523 if ( $matchOrigin ) {
524 $response->header( "Access-Control-Allow-Origin: $originParam" );
525 $response->header( 'Access-Control-Allow-Credentials: true' );
526 $this->getOutput()->addVaryHeader( 'Origin' );
533 * Attempt to match an Origin header against a set of rules and a set of exceptions
534 * @param string $value Origin header
535 * @param array $rules Set of wildcard rules
536 * @param array $exceptions Set of wildcard rules
537 * @return bool True if $value matches a rule in $rules and doesn't match
538 * any rules in $exceptions, false otherwise
540 protected static function matchOrigin( $value, $rules, $exceptions ) {
541 foreach ( $rules as $rule ) {
542 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
543 // Rule matches, check exceptions
544 foreach ( $exceptions as $exc ) {
545 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
558 * Helper function to convert wildcard string into a regex
562 * @param string $wildcard String with wildcards
563 * @return string Regular expression
565 protected static function wildcardToRegex( $wildcard ) {
566 $wildcard = preg_quote( $wildcard, '/' );
567 $wildcard = str_replace(
573 return "/https?:\/\/$wildcard/";
576 protected function sendCacheHeaders() {
577 $response = $this->getRequest()->response();
578 $out = $this->getOutput();
580 $config = $this->getConfig();
582 if ( $config->get( 'VaryOnXFP' ) ) {
583 $out->addVaryHeader( 'X-Forwarded-Proto' );
586 if ( $this->mCacheMode
== 'private' ) {
587 $response->header( 'Cache-Control: private' );
591 $useXVO = $config->get( 'UseXVO' );
592 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
593 $out->addVaryHeader( 'Cookie' );
594 $response->header( $out->getVaryHeader() );
596 $response->header( $out->getXVO() );
597 if ( $out->haveCacheVaryCookies() ) {
598 // Logged in, mark this request private
599 $response->header( 'Cache-Control: private' );
602 // Logged out, send normal public headers below
603 } elseif ( session_id() != '' ) {
604 // Logged in or otherwise has session (e.g. anonymous users who have edited)
605 // Mark request private
606 $response->header( 'Cache-Control: private' );
609 } // else no XVO and anonymous, send public headers below
612 // Send public headers
613 $response->header( $out->getVaryHeader() );
615 $response->header( $out->getXVO() );
618 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
619 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
620 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
622 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
623 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
626 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
627 // Public cache not requested
628 // Sending a Vary header in this case is harmless, and protects us
629 // against conditional calls of setCacheMaxAge().
630 $response->header( 'Cache-Control: private' );
635 $this->mCacheControl
['public'] = true;
637 // Send an Expires header
638 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
639 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
640 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
642 // Construct the Cache-Control header
645 foreach ( $this->mCacheControl
as $name => $value ) {
646 if ( is_bool( $value ) ) {
648 $ccHeader .= $separator . $name;
652 $ccHeader .= $separator . "$name=$value";
657 $response->header( "Cache-Control: $ccHeader" );
661 * Replace the result data with the information about an exception.
662 * Returns the error code
663 * @param Exception $e
666 protected function substituteResultWithError( $e ) {
667 $result = $this->getResult();
669 // Printer may not be initialized if the extractRequestParams() fails for the main module
670 if ( !isset( $this->mPrinter
) ) {
671 // The printer has not been created yet. Try to manually get formatter value.
672 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
673 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
674 $value = self
::API_DEFAULT_FORMAT
;
677 $this->mPrinter
= $this->createPrinterByName( $value );
680 // Printer may not be able to handle errors. This is particularly
681 // likely if the module returns something for getCustomPrinter().
682 if ( !$this->mPrinter
->canPrintErrors() ) {
683 $this->mPrinter
->safeProfileOut();
684 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
687 // Update raw mode flag for the selected printer.
688 $result->setRawMode( $this->mPrinter
->getNeedsRawData() );
690 $config = $this->getConfig();
692 if ( $e instanceof UsageException
) {
693 // User entered incorrect parameters - generate error response
694 $errMessage = $e->getMessageArray();
695 $link = wfExpandUrl( wfScript( 'api' ) );
696 ApiResult
::setContent( $errMessage, "See $link for API usage" );
698 // Something is seriously wrong
699 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
700 $info = 'Database query error';
702 $info = "Exception Caught: {$e->getMessage()}";
706 'code' => 'internal_api_error_' . get_class( $e ),
709 ApiResult
::setContent(
711 $config->get( 'ShowExceptionDetails' ) ?
"\n\n{$e->getTraceAsString()}\n\n" : ''
715 // Remember all the warnings to re-add them later
716 $oldResult = $result->getData();
717 $warnings = isset( $oldResult['warnings'] ) ?
$oldResult['warnings'] : null;
721 $requestid = $this->getParameter( 'requestid' );
722 if ( !is_null( $requestid ) ) {
723 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
725 if ( $config->get( 'ShowHostnames' ) ) {
726 // servedby is especially useful when debugging errors
727 $result->addValue( null, 'servedby', wfHostName(), ApiResult
::NO_SIZE_CHECK
);
729 if ( $warnings !== null ) {
730 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
733 $result->addValue( null, 'error', $errMessage, ApiResult
::NO_SIZE_CHECK
);
735 return $errMessage['code'];
739 * Set up for the execution.
742 protected function setupExecuteAction() {
743 // First add the id to the top element
744 $result = $this->getResult();
745 $requestid = $this->getParameter( 'requestid' );
746 if ( !is_null( $requestid ) ) {
747 $result->addValue( null, 'requestid', $requestid );
750 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
751 $servedby = $this->getParameter( 'servedby' );
753 $result->addValue( null, 'servedby', wfHostName() );
757 if ( $this->getParameter( 'curtimestamp' ) ) {
758 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
759 ApiResult
::NO_SIZE_CHECK
);
762 $params = $this->extractRequestParams();
764 $this->mAction
= $params['action'];
766 if ( !is_string( $this->mAction
) ) {
767 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
774 * Set up the module for response
775 * @return ApiBase The module that will handle this action
777 protected function setupModule() {
778 // Instantiate the module requested by the user
779 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
780 if ( $module === null ) {
781 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
783 $moduleParams = $module->extractRequestParams();
785 // Check token, if necessary
786 if ( $module->needsToken() === true ) {
787 throw new MWException(
788 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
789 "See documentation for ApiBase::needsToken for details."
792 if ( $module->needsToken() ) {
793 if ( !$module->mustBePosted() ) {
794 throw new MWException(
795 "Module '{$module->getModuleName()}' must require POST to use tokens."
799 if ( !isset( $moduleParams['token'] ) ) {
800 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
803 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
805 $module->encodeParamName( 'token' ),
806 $this->getRequest()->getQueryValues()
810 "The '{$module->encodeParamName( 'token' )}' parameter was found in the query string, but must be in the POST body",
815 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
816 $this->dieUsageMsg( 'sessionfailure' );
824 * Check the max lag if necessary
825 * @param ApiBase $module Api module being used
826 * @param array $params Array an array containing the request parameters.
827 * @return bool True on success, false should exit immediately
829 protected function checkMaxLag( $module, $params ) {
830 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
832 $maxLag = $params['maxlag'];
833 list( $host, $lag ) = wfGetLB()->getMaxLag();
834 if ( $lag > $maxLag ) {
835 $response = $this->getRequest()->response();
837 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
838 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
840 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
841 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
844 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
852 * Check for sufficient permissions to execute
853 * @param ApiBase $module An Api module
855 protected function checkExecutePermissions( $module ) {
856 $user = $this->getUser();
857 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
858 !$user->isAllowed( 'read' )
860 $this->dieUsageMsg( 'readrequired' );
862 if ( $module->isWriteMode() ) {
863 if ( !$this->mEnableWrite
) {
864 $this->dieUsageMsg( 'writedisabled' );
866 if ( !$user->isAllowed( 'writeapi' ) ) {
867 $this->dieUsageMsg( 'writerequired' );
869 if ( wfReadOnly() ) {
870 $this->dieReadOnly();
874 // Allow extensions to stop execution for arbitrary reasons.
876 if ( !wfRunHooks( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
877 $this->dieUsageMsg( $message );
882 * Check asserts of the user's rights
883 * @param array $params
885 protected function checkAsserts( $params ) {
886 if ( isset( $params['assert'] ) ) {
887 $user = $this->getUser();
888 switch ( $params['assert'] ) {
890 if ( $user->isAnon() ) {
891 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
895 if ( !$user->isAllowed( 'bot' ) ) {
896 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
904 * Check POST for external response and setup result printer
905 * @param ApiBase $module An Api module
906 * @param array $params An array with the request parameters
908 protected function setupExternalResponse( $module, $params ) {
909 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
910 // Module requires POST. GET request might still be allowed
911 // if $wgDebugApi is true, otherwise fail.
912 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction
) );
915 // See if custom printer is used
916 $this->mPrinter
= $module->getCustomPrinter();
917 if ( is_null( $this->mPrinter
) ) {
918 // Create an appropriate printer
919 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
922 if ( $this->mPrinter
->getNeedsRawData() ) {
923 $this->getResult()->setRawMode();
928 * Execute the actual module, without any error handling
930 protected function executeAction() {
931 $params = $this->setupExecuteAction();
932 $module = $this->setupModule();
933 $this->mModule
= $module;
935 $this->checkExecutePermissions( $module );
937 if ( !$this->checkMaxLag( $module, $params ) ) {
941 if ( !$this->mInternalMode
) {
942 $this->setupExternalResponse( $module, $params );
945 $this->checkAsserts( $params );
948 $module->profileIn();
950 wfRunHooks( 'APIAfterExecute', array( &$module ) );
951 $module->profileOut();
953 $this->reportUnusedParams();
955 if ( !$this->mInternalMode
) {
956 //append Debug information
957 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
960 $this->printResult( false );
965 * Log the preceding request
966 * @param int $time Time in seconds
968 protected function logRequest( $time ) {
969 $request = $this->getRequest();
970 $milliseconds = $time === null ?
'?' : round( $time * 1000 );
972 ' ' . $request->getMethod() .
973 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
974 ' ' . $request->getIP() .
975 ' T=' . $milliseconds . 'ms';
976 foreach ( $this->getParamsUsed() as $name ) {
977 $value = $request->getVal( $name );
978 if ( $value === null ) {
981 $s .= ' ' . $name . '=';
982 if ( strlen( $value ) > 256 ) {
983 $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
984 $s .= $encValue . '[...]';
986 $s .= $this->encodeRequestLogValue( $value );
990 wfDebugLog( 'api', $s, 'private' );
994 * Encode a value in a format suitable for a space-separated log line.
998 protected function encodeRequestLogValue( $s ) {
1001 $chars = ';@$!*(),/:';
1002 $numChars = strlen( $chars );
1003 for ( $i = 0; $i < $numChars; $i++
) {
1004 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1008 return strtr( rawurlencode( $s ), $table );
1012 * Get the request parameters used in the course of the preceding execute() request
1015 protected function getParamsUsed() {
1016 return array_keys( $this->mParamsUsed
);
1020 * Get a request value, and register the fact that it was used, for logging.
1021 * @param string $name
1022 * @param mixed $default
1025 public function getVal( $name, $default = null ) {
1026 $this->mParamsUsed
[$name] = true;
1028 $ret = $this->getRequest()->getVal( $name );
1029 if ( $ret === null ) {
1030 if ( $this->getRequest()->getArray( $name ) !== null ) {
1031 // See bug 10262 for why we don't just join( '|', ... ) the
1034 "Parameter '$name' uses unsupported PHP array syntax"
1043 * Get a boolean request value, and register the fact that the parameter
1044 * was used, for logging.
1045 * @param string $name
1048 public function getCheck( $name ) {
1049 return $this->getVal( $name, null ) !== null;
1053 * Get a request upload, and register the fact that it was used, for logging.
1056 * @param string $name Parameter name
1057 * @return WebRequestUpload
1059 public function getUpload( $name ) {
1060 $this->mParamsUsed
[$name] = true;
1062 return $this->getRequest()->getUpload( $name );
1066 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1067 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1069 protected function reportUnusedParams() {
1070 $paramsUsed = $this->getParamsUsed();
1071 $allParams = $this->getRequest()->getValueNames();
1073 if ( !$this->mInternalMode
) {
1074 // Printer has not yet executed; don't warn that its parameters are unused
1075 $printerParams = array_map(
1076 array( $this->mPrinter
, 'encodeParamName' ),
1077 array_keys( $this->mPrinter
->getFinalParams() ?
: array() )
1079 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1081 $unusedParams = array_diff( $allParams, $paramsUsed );
1084 if ( count( $unusedParams ) ) {
1085 $s = count( $unusedParams ) > 1 ?
's' : '';
1086 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1091 * Print results using the current printer
1093 * @param bool $isError
1095 protected function printResult( $isError ) {
1096 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1097 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1100 $this->getResult()->cleanUpUTF8();
1101 $printer = $this->mPrinter
;
1102 $printer->profileIn();
1104 $printer->initPrinter( false );
1106 $printer->execute();
1107 $printer->closePrinter();
1108 $printer->profileOut();
1114 public function isReadMode() {
1119 * See ApiBase for description.
1123 public function getAllowedParams() {
1128 ApiBase
::PARAM_DFLT
=> 'help',
1129 ApiBase
::PARAM_TYPE
=> 'submodule',
1132 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1133 ApiBase
::PARAM_TYPE
=> 'submodule',
1136 ApiBase
::PARAM_TYPE
=> 'integer'
1139 ApiBase
::PARAM_TYPE
=> 'integer',
1140 ApiBase
::PARAM_DFLT
=> 0
1143 ApiBase
::PARAM_TYPE
=> 'integer',
1144 ApiBase
::PARAM_DFLT
=> 0
1147 ApiBase
::PARAM_TYPE
=> array( 'user', 'bot' )
1149 'requestid' => null,
1150 'servedby' => false,
1151 'curtimestamp' => false,
1154 ApiBase
::PARAM_DFLT
=> $wgContLang->getCode(),
1159 /** @see ApiBase::getExamplesMessages() */
1160 public function getExamplesMessages() {
1163 => 'apihelp-help-example-main',
1164 'action=help&recursivesubmodules=1'
1165 => 'apihelp-help-example-recursive',
1169 public function modifyHelp( array &$help, array $options ) {
1170 // Wish PHP had an "array_insert_before". Instead, we have to manually
1171 // reindex the array to get 'permissions' in the right place.
1174 foreach ( $oldHelp as $k => $v ) {
1175 if ( $k === 'submodules' ) {
1176 $help['permissions'] = '';
1180 $help['credits'] = '';
1182 // Fill 'permissions'
1183 $help['permissions'] .= Html
::openElement( 'div',
1184 array( 'class' => 'apihelp-block apihelp-permissions' ) );
1185 $m = $this->msg( 'api-help-permissions' );
1186 if ( !$m->isDisabled() ) {
1187 $help['permissions'] .= Html
::rawElement( 'div', array( 'class' => 'apihelp-block-head' ),
1188 $m->numParams( count( self
::$mRights ) )->parse()
1191 $help['permissions'] .= Html
::openElement( 'dl' );
1192 foreach ( self
::$mRights as $right => $rightMsg ) {
1193 $help['permissions'] .= Html
::element( 'dt', null, $right );
1195 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1196 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1198 $groups = array_map( function ( $group ) {
1199 return $group == '*' ?
'all' : $group;
1200 }, User
::getGroupsWithPermission( $right ) );
1202 $help['permissions'] .= Html
::rawElement( 'dd', null,
1203 $this->msg( 'api-help-permissions-granted-to' )
1204 ->numParams( count( $groups ) )
1205 ->params( $this->getLanguage()->commaList( $groups ) )
1209 $help['permissions'] .= Html
::closeElement( 'dl' );
1210 $help['permissions'] .= Html
::closeElement( 'div' );
1212 // Fill 'credits', if applicable
1213 if ( empty( $options['nolead'] ) ) {
1214 $help['credits'] .= Html
::element( 'h' . min( 6, $options['headerlevel'] +
1 ),
1215 array( 'id' => '+credits', 'class' => 'apihelp-header' ),
1216 $this->msg( 'api-credits-header' )->parse()
1218 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1222 private $mCanApiHighLimits = null;
1225 * Check whether the current user is allowed to use high limits
1228 public function canApiHighLimits() {
1229 if ( !isset( $this->mCanApiHighLimits
) ) {
1230 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1233 return $this->mCanApiHighLimits
;
1237 * Overrides to return this instance's module manager.
1238 * @return ApiModuleManager
1240 public function getModuleManager() {
1241 return $this->mModuleMgr
;
1244 /************************************************************************//**
1250 * Sets whether the pretty-printer should format *bold* and $italics$
1252 * @deprecated since 1.25
1255 public function setHelp( $help = true ) {
1256 wfDeprecated( __METHOD__
, '1.25' );
1257 $this->mPrinter
->setHelp( $help );
1261 * Override the parent to generate help messages for all available modules.
1263 * @deprecated since 1.25
1266 public function makeHelpMsg() {
1267 wfDeprecated( __METHOD__
, '1.25' );
1270 // Get help text from cache if present
1271 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1272 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) ) );
1274 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1275 if ( $cacheHelpTimeout > 0 ) {
1276 $cached = $wgMemc->get( $key );
1281 $retval = $this->reallyMakeHelpMsg();
1282 if ( $cacheHelpTimeout > 0 ) {
1283 $wgMemc->set( $key, $retval, $cacheHelpTimeout );
1290 * @deprecated since 1.25
1291 * @return mixed|string
1293 public function reallyMakeHelpMsg() {
1294 wfDeprecated( __METHOD__
, '1.25' );
1297 // Use parent to make default message for the main module
1298 $msg = parent
::makeHelpMsg();
1300 $astriks = str_repeat( '*** ', 14 );
1301 $msg .= "\n\n$astriks Modules $astriks\n\n";
1303 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1304 $module = $this->mModuleMgr
->getModule( $name );
1305 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1307 $msg2 = $module->makeHelpMsg();
1308 if ( $msg2 !== false ) {
1314 $msg .= "\n$astriks Permissions $astriks\n\n";
1315 foreach ( self
::$mRights as $right => $rightMsg ) {
1316 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1317 ->useDatabase( false )
1318 ->inLanguage( 'en' )
1320 $groups = User
::getGroupsWithPermission( $right );
1321 $msg .= "* " . $right . " *\n $rightsMsg" .
1322 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1325 $msg .= "\n$astriks Formats $astriks\n\n";
1326 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1327 $module = $this->mModuleMgr
->getModule( $name );
1328 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1329 $msg2 = $module->makeHelpMsg();
1330 if ( $msg2 !== false ) {
1336 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1337 $credits = str_replace( "\n", "\n ", $credits );
1338 $msg .= "\n*** Credits: ***\n $credits\n";
1344 * @deprecated since 1.25
1345 * @param ApiBase $module
1346 * @param string $paramName What type of request is this? e.g. action,
1347 * query, list, prop, meta, format
1350 public static function makeHelpMsgHeader( $module, $paramName ) {
1351 wfDeprecated( __METHOD__
, '1.25' );
1352 $modulePrefix = $module->getModulePrefix();
1353 if ( strval( $modulePrefix ) !== '' ) {
1354 $modulePrefix = "($modulePrefix) ";
1357 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1361 * Check whether the user wants us to show version information in the API help
1363 * @deprecated since 1.21, always returns false
1365 public function getShowVersions() {
1366 wfDeprecated( __METHOD__
, '1.21' );
1372 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1373 * classes who wish to add their own modules to their lexicon or override the
1374 * behavior of inherent ones.
1376 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1377 * @param string $name The identifier for this module.
1378 * @param ApiBase $class The class where this module is implemented.
1380 protected function addModule( $name, $class ) {
1381 $this->getModuleManager()->addModule( $name, 'action', $class );
1385 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1386 * classes who wish to add to or modify current formatters.
1388 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1389 * @param string $name The identifier for this format.
1390 * @param ApiFormatBase $class The class implementing this format.
1392 protected function addFormat( $name, $class ) {
1393 $this->getModuleManager()->addModule( $name, 'format', $class );
1397 * Get the array mapping module names to class names
1398 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1401 function getModules() {
1402 return $this->getModuleManager()->getNamesWithClasses( 'action' );
1406 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1409 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1412 public function getFormats() {
1413 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1421 * This exception will be thrown when dieUsage is called to stop module execution.
1425 class UsageException
extends MWException
{
1432 private $mExtraData;
1435 * @param string $message
1436 * @param string $codestr
1438 * @param array|null $extradata
1440 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1441 parent
::__construct( $message, $code );
1442 $this->mCodestr
= $codestr;
1443 $this->mExtraData
= $extradata;
1449 public function getCodeString() {
1450 return $this->mCodestr
;
1456 public function getMessageArray() {
1458 'code' => $this->mCodestr
,
1459 'info' => $this->getMessage()
1461 if ( is_array( $this->mExtraData
) ) {
1462 $result = array_merge( $result, $this->mExtraData
);
1471 public function __toString() {
1472 return "{$this->getCodeString()}: {$this->getMessage()}";
1477 * For really cool vim folding this needs to be at the end:
1478 * vim: foldmarker=@{,@} foldmethod=marker