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',
95 * List of available formats: format name => format class
97 private static $Formats = array(
98 'json' => 'ApiFormatJson',
99 'jsonfm' => 'ApiFormatJson',
100 'php' => 'ApiFormatPhp',
101 'phpfm' => 'ApiFormatPhp',
102 'wddx' => 'ApiFormatWddx',
103 'wddxfm' => 'ApiFormatWddx',
104 'xml' => 'ApiFormatXml',
105 'xmlfm' => 'ApiFormatXml',
106 'yaml' => 'ApiFormatYaml',
107 'yamlfm' => 'ApiFormatYaml',
108 'rawfm' => 'ApiFormatJson',
109 'txt' => 'ApiFormatTxt',
110 'txtfm' => 'ApiFormatTxt',
111 'dbg' => 'ApiFormatDbg',
112 'dbgfm' => 'ApiFormatDbg',
113 'dump' => 'ApiFormatDump',
114 'dumpfm' => 'ApiFormatDump',
115 'none' => 'ApiFormatNone',
118 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
120 * List of user roles that are specifically relevant to the API.
121 * array( 'right' => array ( 'msg' => 'Some message with a $1',
122 * 'params' => array ( $someVarToSubst ) ),
125 private static $mRights = array(
127 'msg' => 'right-writeapi',
130 'apihighlimits' => array(
131 'msg' => 'api-help-right-apihighlimits',
132 'params' => array( ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
)
135 // @codingStandardsIgnoreEnd
142 private $mModuleMgr, $mResult;
144 private $mEnableWrite;
145 private $mInternalMode, $mSquidMaxage, $mModule;
147 private $mCacheMode = 'private';
148 private $mCacheControl = array();
149 private $mParamsUsed = array();
152 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
154 * @param IContextSource|WebRequest $context If this is an instance of
155 * FauxRequest, errors are thrown and no printing occurs
156 * @param bool $enableWrite Should be set to true if the api may modify data
158 public function __construct( $context = null, $enableWrite = false ) {
159 if ( $context === null ) {
160 $context = RequestContext
::getMain();
161 } elseif ( $context instanceof WebRequest
) {
164 $context = RequestContext
::getMain();
166 // We set a derivative context so we can change stuff later
167 $this->setContext( new DerivativeContext( $context ) );
169 if ( isset( $request ) ) {
170 $this->getContext()->setRequest( $request );
173 $this->mInternalMode
= ( $this->getRequest() instanceof FauxRequest
);
175 // Special handling for the main module: $parent === $this
176 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
178 if ( !$this->mInternalMode
) {
179 // Impose module restrictions.
180 // If the current user cannot read,
181 // Remove all modules other than login
184 if ( $this->getVal( 'callback' ) !== null ) {
185 // JSON callback allows cross-site reads.
186 // For safety, strip user credentials.
187 wfDebug( "API: stripping user credentials for JSON callback\n" );
188 $wgUser = new User();
189 $this->getContext()->setUser( $wgUser );
193 $uselang = $this->getParameter( 'uselang' );
194 if ( $uselang === 'user' ) {
195 // Assume the parent context is going to return the user language
196 // for uselang=user (see T85635).
198 if ( $uselang === 'content' ) {
200 $uselang = $wgContLang->getCode();
202 $code = RequestContext
::sanitizeLangCode( $uselang );
203 $this->getContext()->setLanguage( $code );
204 if ( !$this->mInternalMode
) {
206 $wgLang = $this->getContext()->getLanguage();
207 RequestContext
::getMain()->setLanguage( $wgLang );
211 $config = $this->getConfig();
212 $this->mModuleMgr
= new ApiModuleManager( $this );
213 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
214 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
215 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
216 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
218 $this->mResult
= new ApiResult( $this );
219 $this->mEnableWrite
= $enableWrite;
221 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
222 $this->mCommit
= false;
226 * Return true if the API was started by other PHP code using FauxRequest
229 public function isInternalMode() {
230 return $this->mInternalMode
;
234 * Get the ApiResult object associated with current request
238 public function getResult() {
239 return $this->mResult
;
243 * Get the API module object. Only works after executeAction()
247 public function getModule() {
248 return $this->mModule
;
252 * Get the result formatter object. Only works after setupExecuteAction()
254 * @return ApiFormatBase
256 public function getPrinter() {
257 return $this->mPrinter
;
261 * Set how long the response should be cached.
265 public function setCacheMaxAge( $maxage ) {
266 $this->setCacheControl( array(
267 'max-age' => $maxage,
268 's-maxage' => $maxage
273 * Set the type of caching headers which will be sent.
275 * @param string $mode One of:
276 * - 'public': Cache this object in public caches, if the maxage or smaxage
277 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
278 * not provided by any of these means, the object will be private.
279 * - 'private': Cache this object only in private client-side caches.
280 * - 'anon-public-user-private': Make this object cacheable for logged-out
281 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
282 * set consistently for a given URL, it cannot be set differently depending on
283 * things like the contents of the database, or whether the user is logged in.
285 * If the wiki does not allow anonymous users to read it, the mode set here
286 * will be ignored, and private caching headers will always be sent. In other words,
287 * the "public" mode is equivalent to saying that the data sent is as public as a page
290 * For user-dependent data, the private mode should generally be used. The
291 * anon-public-user-private mode should only be used where there is a particularly
292 * good performance reason for caching the anonymous response, but where the
293 * response to logged-in users may differ, or may contain private data.
295 * If this function is never called, then the default will be the private mode.
297 public function setCacheMode( $mode ) {
298 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
299 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
301 // Ignore for forwards-compatibility
305 if ( !User
::isEveryoneAllowed( 'read' ) ) {
306 // Private wiki, only private headers
307 if ( $mode !== 'private' ) {
308 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
314 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
315 // User language is used for i18n, so we don't want to publicly
316 // cache. Anons are ok, because if they have non-default language
317 // then there's an appropriate Vary header set by whatever set
318 // their non-default language.
319 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
320 "'anon-public-user-private' due to uselang=user\n" );
321 $mode = 'anon-public-user-private';
324 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
325 $this->mCacheMode
= $mode;
329 * Set directives (key/value pairs) for the Cache-Control header.
330 * Boolean values will be formatted as such, by including or omitting
331 * without an equals sign.
333 * Cache control values set here will only be used if the cache mode is not
334 * private, see setCacheMode().
336 * @param array $directives
338 public function setCacheControl( $directives ) {
339 $this->mCacheControl
= $directives +
$this->mCacheControl
;
343 * Create an instance of an output formatter by its name
345 * @param string $format
347 * @return ApiFormatBase
349 public function createPrinterByName( $format ) {
350 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
351 if ( $printer === null ) {
352 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
359 * Execute api request. Any errors will be handled if the API was called by the remote client.
361 public function execute() {
363 if ( $this->mInternalMode
) {
364 $this->executeAction();
366 $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
420 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
423 // Allow extra cleanup and logging
424 Hooks
::run( 'ApiMain::onException', array( $this, $e ) );
427 if ( !( $e instanceof UsageException
) ) {
428 MWExceptionHandler
::logException( $e );
431 // Handle any kind of exception by outputting properly formatted error message.
432 // If this fails, an unhandled exception should be thrown so that global error
433 // handler will process and log it.
435 $errCode = $this->substituteResultWithError( $e );
437 // Error results should not be cached
438 $this->setCacheMode( 'private' );
440 $response = $this->getRequest()->response();
441 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
442 if ( $e->getCode() === 0 ) {
443 $response->header( $headerStr );
445 $response->header( $headerStr, true, $e->getCode() );
448 // Reset and print just the error message
451 // If the error occurred during printing, do a printer->profileOut()
452 $this->mPrinter
->safeProfileOut();
453 $this->printResult( true );
457 * Handle an exception from the ApiBeforeMain hook.
459 * This tries to print the exception as an API response, to be more
460 * friendly to clients. If it fails, it will rethrow the exception.
463 * @param Exception $e
466 public static function handleApiBeforeMainException( Exception
$e ) {
470 $main = new self( RequestContext
::getMain(), false );
471 $main->handleException( $e );
472 } catch ( Exception
$e2 ) {
473 // Nope, even that didn't work. Punt.
477 // Log the request and reset cache headers
478 $main->logRequest( 0 );
479 $main->sendCacheHeaders();
485 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
487 * If no origin parameter is present, nothing happens.
488 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
489 * is set and false is returned.
490 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
491 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
493 * http://www.w3.org/TR/cors/#resource-requests
494 * http://www.w3.org/TR/cors/#resource-preflight-requests
496 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
498 protected function handleCORS() {
499 $originParam = $this->getParameter( 'origin' ); // defaults to null
500 if ( $originParam === null ) {
501 // No origin parameter, nothing to do
505 $request = $this->getRequest();
506 $response = $request->response();
508 // Origin: header is a space-separated list of origins, check all of them
509 $originHeader = $request->getHeader( 'Origin' );
510 if ( $originHeader === false ) {
513 $originHeader = trim( $originHeader );
514 $origins = preg_split( '/\s+/', $originHeader );
517 if ( !in_array( $originParam, $origins ) ) {
518 // origin parameter set but incorrect
519 // Send a 403 response
520 $message = HttpStatus
::getMessage( 403 );
521 $response->header( "HTTP/1.1 403 $message", true, 403 );
522 $response->header( 'Cache-Control: no-cache' );
523 echo "'origin' parameter does not match Origin header\n";
528 $config = $this->getConfig();
529 $matchOrigin = count( $origins ) === 1 && self
::matchOrigin(
531 $config->get( 'CrossSiteAJAXdomains' ),
532 $config->get( 'CrossSiteAJAXdomainExceptions' )
535 if ( $matchOrigin ) {
536 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
537 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
539 // This is a CORS preflight request
540 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
541 // If method is not a case-sensitive match, do not set any additional headers and terminate.
544 // We allow the actual request to send the following headers
545 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
546 if ( $requestedHeaders !== false ) {
547 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
550 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
553 // We only allow the actual request to be GET or POST
554 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
557 $response->header( "Access-Control-Allow-Origin: $originHeader" );
558 $response->header( 'Access-Control-Allow-Credentials: true' );
559 $response->header( "Timing-Allow-Origin: $originHeader" ); # http://www.w3.org/TR/resource-timing/#timing-allow-origin
562 $response->header( 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag' );
566 $this->getOutput()->addVaryHeader( 'Origin' );
571 * Attempt to match an Origin header against a set of rules and a set of exceptions
572 * @param string $value Origin header
573 * @param array $rules Set of wildcard rules
574 * @param array $exceptions Set of wildcard rules
575 * @return bool True if $value matches a rule in $rules and doesn't match
576 * any rules in $exceptions, false otherwise
578 protected static function matchOrigin( $value, $rules, $exceptions ) {
579 foreach ( $rules as $rule ) {
580 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
581 // Rule matches, check exceptions
582 foreach ( $exceptions as $exc ) {
583 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
596 * Attempt to validate the value of Access-Control-Request-Headers against a list
597 * of headers that we allow the follow up request to send.
599 * @param string $requestedHeaders Comma seperated list of HTTP headers
600 * @return bool True if all requested headers are in the list of allowed headers
602 protected static function matchRequestedHeaders( $requestedHeaders ) {
603 if ( trim( $requestedHeaders ) === '' ) {
606 $requestedHeaders = explode( ',', $requestedHeaders );
607 $allowedAuthorHeaders = array_flip( array(
608 /* simple headers (see spec) */
613 /* non-authorable headers in XHR, which are however requested by some UAs */
617 /* MediaWiki whitelist */
620 foreach ( $requestedHeaders as $rHeader ) {
621 $rHeader = strtolower( trim( $rHeader ) );
622 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
623 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
631 * Helper function to convert wildcard string into a regex
635 * @param string $wildcard String with wildcards
636 * @return string Regular expression
638 protected static function wildcardToRegex( $wildcard ) {
639 $wildcard = preg_quote( $wildcard, '/' );
640 $wildcard = str_replace(
646 return "/^https?:\/\/$wildcard$/";
649 protected function sendCacheHeaders() {
650 $response = $this->getRequest()->response();
651 $out = $this->getOutput();
653 $config = $this->getConfig();
655 if ( $config->get( 'VaryOnXFP' ) ) {
656 $out->addVaryHeader( 'X-Forwarded-Proto' );
659 if ( $this->mCacheMode
== 'private' ) {
660 $response->header( 'Cache-Control: private' );
664 $useXVO = $config->get( 'UseXVO' );
665 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
666 $out->addVaryHeader( 'Cookie' );
667 $response->header( $out->getVaryHeader() );
669 $response->header( $out->getXVO() );
670 if ( $out->haveCacheVaryCookies() ) {
671 // Logged in, mark this request private
672 $response->header( 'Cache-Control: private' );
675 // Logged out, send normal public headers below
676 } elseif ( session_id() != '' ) {
677 // Logged in or otherwise has session (e.g. anonymous users who have edited)
678 // Mark request private
679 $response->header( 'Cache-Control: private' );
682 } // else no XVO and anonymous, send public headers below
685 // Send public headers
686 $response->header( $out->getVaryHeader() );
688 $response->header( $out->getXVO() );
691 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
692 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
693 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
695 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
696 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
699 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
700 // Public cache not requested
701 // Sending a Vary header in this case is harmless, and protects us
702 // against conditional calls of setCacheMaxAge().
703 $response->header( 'Cache-Control: private' );
708 $this->mCacheControl
['public'] = true;
710 // Send an Expires header
711 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
712 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
713 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
715 // Construct the Cache-Control header
718 foreach ( $this->mCacheControl
as $name => $value ) {
719 if ( is_bool( $value ) ) {
721 $ccHeader .= $separator . $name;
725 $ccHeader .= $separator . "$name=$value";
730 $response->header( "Cache-Control: $ccHeader" );
734 * Replace the result data with the information about an exception.
735 * Returns the error code
736 * @param Exception $e
739 protected function substituteResultWithError( $e ) {
740 $result = $this->getResult();
742 // Printer may not be initialized if the extractRequestParams() fails for the main module
743 if ( !isset( $this->mPrinter
) ) {
744 // The printer has not been created yet. Try to manually get formatter value.
745 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
746 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
747 $value = self
::API_DEFAULT_FORMAT
;
750 $this->mPrinter
= $this->createPrinterByName( $value );
753 // Printer may not be able to handle errors. This is particularly
754 // likely if the module returns something for getCustomPrinter().
755 if ( !$this->mPrinter
->canPrintErrors() ) {
756 $this->mPrinter
->safeProfileOut();
757 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
760 // Update raw mode flag for the selected printer.
761 $result->setRawMode( $this->mPrinter
->getNeedsRawData() );
763 $config = $this->getConfig();
765 if ( $e instanceof UsageException
) {
766 // User entered incorrect parameters - generate error response
767 $errMessage = $e->getMessageArray();
768 $link = wfExpandUrl( wfScript( 'api' ) );
769 ApiResult
::setContent( $errMessage, "See $link for API usage" );
771 // Something is seriously wrong
772 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
773 $info = 'Database query error';
775 $info = "Exception Caught: {$e->getMessage()}";
779 'code' => 'internal_api_error_' . get_class( $e ),
780 'info' => '[' . MWExceptionHandler
::getLogId( $e ) . '] ' . $info,
782 if ( $config->get( 'ShowExceptionDetails' ) ) {
783 ApiResult
::setContent(
785 MWExceptionHandler
::getRedactedTraceAsString( $e )
790 // Remember all the warnings to re-add them later
791 $oldResult = $result->getData();
792 $warnings = isset( $oldResult['warnings'] ) ?
$oldResult['warnings'] : null;
796 $requestid = $this->getParameter( 'requestid' );
797 if ( !is_null( $requestid ) ) {
798 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
800 if ( $config->get( 'ShowHostnames' ) ) {
801 // servedby is especially useful when debugging errors
802 $result->addValue( null, 'servedby', wfHostName(), ApiResult
::NO_SIZE_CHECK
);
804 if ( $warnings !== null ) {
805 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
808 $result->addValue( null, 'error', $errMessage, ApiResult
::NO_SIZE_CHECK
);
810 return $errMessage['code'];
814 * Set up for the execution.
817 protected function setupExecuteAction() {
818 // First add the id to the top element
819 $result = $this->getResult();
820 $requestid = $this->getParameter( 'requestid' );
821 if ( !is_null( $requestid ) ) {
822 $result->addValue( null, 'requestid', $requestid );
825 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
826 $servedby = $this->getParameter( 'servedby' );
828 $result->addValue( null, 'servedby', wfHostName() );
832 if ( $this->getParameter( 'curtimestamp' ) ) {
833 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
834 ApiResult
::NO_SIZE_CHECK
);
837 $params = $this->extractRequestParams();
839 $this->mAction
= $params['action'];
841 if ( !is_string( $this->mAction
) ) {
842 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
849 * Set up the module for response
850 * @return ApiBase The module that will handle this action
851 * @throws MWException
852 * @throws UsageException
854 protected function setupModule() {
855 // Instantiate the module requested by the user
856 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
857 if ( $module === null ) {
858 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
860 $moduleParams = $module->extractRequestParams();
862 // Check token, if necessary
863 if ( $module->needsToken() === true ) {
864 throw new MWException(
865 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
866 "See documentation for ApiBase::needsToken for details."
869 if ( $module->needsToken() ) {
870 if ( !$module->mustBePosted() ) {
871 throw new MWException(
872 "Module '{$module->getModuleName()}' must require POST to use tokens."
876 if ( !isset( $moduleParams['token'] ) ) {
877 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
880 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
882 $module->encodeParamName( 'token' ),
883 $this->getRequest()->getQueryValues()
887 "The '{$module->encodeParamName( 'token' )}' parameter was found in the query string, but must be in the POST body",
892 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
893 $this->dieUsageMsg( 'sessionfailure' );
901 * Check the max lag if necessary
902 * @param ApiBase $module Api module being used
903 * @param array $params Array an array containing the request parameters.
904 * @return bool True on success, false should exit immediately
906 protected function checkMaxLag( $module, $params ) {
907 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
909 $maxLag = $params['maxlag'];
910 list( $host, $lag ) = wfGetLB()->getMaxLag();
911 if ( $lag > $maxLag ) {
912 $response = $this->getRequest()->response();
914 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
915 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
917 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
918 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
921 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
929 * Check for sufficient permissions to execute
930 * @param ApiBase $module An Api module
932 protected function checkExecutePermissions( $module ) {
933 $user = $this->getUser();
934 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
935 !$user->isAllowed( 'read' )
937 $this->dieUsageMsg( 'readrequired' );
939 if ( $module->isWriteMode() ) {
940 if ( !$this->mEnableWrite
) {
941 $this->dieUsageMsg( 'writedisabled' );
943 if ( !$user->isAllowed( 'writeapi' ) ) {
944 $this->dieUsageMsg( 'writerequired' );
946 if ( wfReadOnly() ) {
947 $this->dieReadOnly();
951 // Allow extensions to stop execution for arbitrary reasons.
953 if ( !Hooks
::run( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
954 $this->dieUsageMsg( $message );
959 * Check asserts of the user's rights
960 * @param array $params
962 protected function checkAsserts( $params ) {
963 if ( isset( $params['assert'] ) ) {
964 $user = $this->getUser();
965 switch ( $params['assert'] ) {
967 if ( $user->isAnon() ) {
968 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
972 if ( !$user->isAllowed( 'bot' ) ) {
973 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
981 * Check POST for external response and setup result printer
982 * @param ApiBase $module An Api module
983 * @param array $params An array with the request parameters
985 protected function setupExternalResponse( $module, $params ) {
986 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
987 // Module requires POST. GET request might still be allowed
988 // if $wgDebugApi is true, otherwise fail.
989 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction
) );
992 // See if custom printer is used
993 $this->mPrinter
= $module->getCustomPrinter();
994 if ( is_null( $this->mPrinter
) ) {
995 // Create an appropriate printer
996 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
999 if ( $this->mPrinter
->getNeedsRawData() ) {
1000 $this->getResult()->setRawMode();
1005 * Execute the actual module, without any error handling
1007 protected function executeAction() {
1008 $params = $this->setupExecuteAction();
1009 $module = $this->setupModule();
1010 $this->mModule
= $module;
1012 $this->checkExecutePermissions( $module );
1014 if ( !$this->checkMaxLag( $module, $params ) ) {
1018 if ( !$this->mInternalMode
) {
1019 $this->setupExternalResponse( $module, $params );
1022 $this->checkAsserts( $params );
1025 $module->profileIn();
1027 Hooks
::run( 'APIAfterExecute', array( &$module ) );
1028 $module->profileOut();
1030 $this->reportUnusedParams();
1032 if ( !$this->mInternalMode
) {
1033 //append Debug information
1034 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1036 // Print result data
1037 $this->printResult( false );
1042 * Log the preceding request
1043 * @param int $time Time in seconds
1045 protected function logRequest( $time ) {
1046 $request = $this->getRequest();
1047 $milliseconds = $time === null ?
'?' : round( $time * 1000 );
1049 ' ' . $request->getMethod() .
1050 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1051 ' ' . $request->getIP() .
1052 ' T=' . $milliseconds . 'ms';
1053 foreach ( $this->getParamsUsed() as $name ) {
1054 $value = $request->getVal( $name );
1055 if ( $value === null ) {
1058 $s .= ' ' . $name . '=';
1059 if ( strlen( $value ) > 256 ) {
1060 $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
1061 $s .= $encValue . '[...]';
1063 $s .= $this->encodeRequestLogValue( $value );
1067 wfDebugLog( 'api', $s, 'private' );
1071 * Encode a value in a format suitable for a space-separated log line.
1075 protected function encodeRequestLogValue( $s ) {
1078 $chars = ';@$!*(),/:';
1079 $numChars = strlen( $chars );
1080 for ( $i = 0; $i < $numChars; $i++
) {
1081 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1085 return strtr( rawurlencode( $s ), $table );
1089 * Get the request parameters used in the course of the preceding execute() request
1092 protected function getParamsUsed() {
1093 return array_keys( $this->mParamsUsed
);
1097 * Get a request value, and register the fact that it was used, for logging.
1098 * @param string $name
1099 * @param mixed $default
1102 public function getVal( $name, $default = null ) {
1103 $this->mParamsUsed
[$name] = true;
1105 $ret = $this->getRequest()->getVal( $name );
1106 if ( $ret === null ) {
1107 if ( $this->getRequest()->getArray( $name ) !== null ) {
1108 // See bug 10262 for why we don't just join( '|', ... ) the
1111 "Parameter '$name' uses unsupported PHP array syntax"
1120 * Get a boolean request value, and register the fact that the parameter
1121 * was used, for logging.
1122 * @param string $name
1125 public function getCheck( $name ) {
1126 return $this->getVal( $name, null ) !== null;
1130 * Get a request upload, and register the fact that it was used, for logging.
1133 * @param string $name Parameter name
1134 * @return WebRequestUpload
1136 public function getUpload( $name ) {
1137 $this->mParamsUsed
[$name] = true;
1139 return $this->getRequest()->getUpload( $name );
1143 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1144 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1146 protected function reportUnusedParams() {
1147 $paramsUsed = $this->getParamsUsed();
1148 $allParams = $this->getRequest()->getValueNames();
1150 if ( !$this->mInternalMode
) {
1151 // Printer has not yet executed; don't warn that its parameters are unused
1152 $printerParams = array_map(
1153 array( $this->mPrinter
, 'encodeParamName' ),
1154 array_keys( $this->mPrinter
->getFinalParams() ?
: array() )
1156 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1158 $unusedParams = array_diff( $allParams, $paramsUsed );
1161 if ( count( $unusedParams ) ) {
1162 $s = count( $unusedParams ) > 1 ?
's' : '';
1163 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1168 * Print results using the current printer
1170 * @param bool $isError
1172 protected function printResult( $isError ) {
1173 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1174 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1177 $this->getResult()->cleanUpUTF8();
1178 $printer = $this->mPrinter
;
1179 $printer->profileIn();
1181 $printer->initPrinter( false );
1183 $printer->execute();
1184 $printer->closePrinter();
1185 $printer->profileOut();
1191 public function isReadMode() {
1196 * See ApiBase for description.
1200 public function getAllowedParams() {
1203 ApiBase
::PARAM_DFLT
=> 'help',
1204 ApiBase
::PARAM_TYPE
=> 'submodule',
1207 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1208 ApiBase
::PARAM_TYPE
=> 'submodule',
1211 ApiBase
::PARAM_TYPE
=> 'integer'
1214 ApiBase
::PARAM_TYPE
=> 'integer',
1215 ApiBase
::PARAM_DFLT
=> 0
1218 ApiBase
::PARAM_TYPE
=> 'integer',
1219 ApiBase
::PARAM_DFLT
=> 0
1222 ApiBase
::PARAM_TYPE
=> array( 'user', 'bot' )
1224 'requestid' => null,
1225 'servedby' => false,
1226 'curtimestamp' => false,
1229 ApiBase
::PARAM_DFLT
=> 'user',
1234 /** @see ApiBase::getExamplesMessages() */
1235 protected function getExamplesMessages() {
1238 => 'apihelp-help-example-main',
1239 'action=help&recursivesubmodules=1'
1240 => 'apihelp-help-example-recursive',
1244 public function modifyHelp( array &$help, array $options ) {
1245 // Wish PHP had an "array_insert_before". Instead, we have to manually
1246 // reindex the array to get 'permissions' in the right place.
1249 foreach ( $oldHelp as $k => $v ) {
1250 if ( $k === 'submodules' ) {
1251 $help['permissions'] = '';
1255 $help['credits'] = '';
1257 // Fill 'permissions'
1258 $help['permissions'] .= Html
::openElement( 'div',
1259 array( 'class' => 'apihelp-block apihelp-permissions' ) );
1260 $m = $this->msg( 'api-help-permissions' );
1261 if ( !$m->isDisabled() ) {
1262 $help['permissions'] .= Html
::rawElement( 'div', array( 'class' => 'apihelp-block-head' ),
1263 $m->numParams( count( self
::$mRights ) )->parse()
1266 $help['permissions'] .= Html
::openElement( 'dl' );
1267 foreach ( self
::$mRights as $right => $rightMsg ) {
1268 $help['permissions'] .= Html
::element( 'dt', null, $right );
1270 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1271 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1273 $groups = array_map( function ( $group ) {
1274 return $group == '*' ?
'all' : $group;
1275 }, User
::getGroupsWithPermission( $right ) );
1277 $help['permissions'] .= Html
::rawElement( 'dd', null,
1278 $this->msg( 'api-help-permissions-granted-to' )
1279 ->numParams( count( $groups ) )
1280 ->params( $this->getLanguage()->commaList( $groups ) )
1284 $help['permissions'] .= Html
::closeElement( 'dl' );
1285 $help['permissions'] .= Html
::closeElement( 'div' );
1287 // Fill 'credits', if applicable
1288 if ( empty( $options['nolead'] ) ) {
1289 $help['credits'] .= Html
::element( 'h' . min( 6, $options['headerlevel'] +
1 ),
1290 array( 'id' => '+credits', 'class' => 'apihelp-header' ),
1291 $this->msg( 'api-credits-header' )->parse()
1293 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1297 private $mCanApiHighLimits = null;
1300 * Check whether the current user is allowed to use high limits
1303 public function canApiHighLimits() {
1304 if ( !isset( $this->mCanApiHighLimits
) ) {
1305 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1308 return $this->mCanApiHighLimits
;
1312 * Overrides to return this instance's module manager.
1313 * @return ApiModuleManager
1315 public function getModuleManager() {
1316 return $this->mModuleMgr
;
1320 * Fetches the user agent used for this request
1322 * The value will be the combination of the 'Api-User-Agent' header (if
1323 * any) and the standard User-Agent header (if any).
1327 public function getUserAgent() {
1329 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1330 $this->getRequest()->getHeader( 'User-agent' )
1334 /************************************************************************//**
1340 * Sets whether the pretty-printer should format *bold* and $italics$
1342 * @deprecated since 1.25
1345 public function setHelp( $help = true ) {
1346 wfDeprecated( __METHOD__
, '1.25' );
1347 $this->mPrinter
->setHelp( $help );
1351 * Override the parent to generate help messages for all available modules.
1353 * @deprecated since 1.25
1356 public function makeHelpMsg() {
1357 wfDeprecated( __METHOD__
, '1.25' );
1360 // Get help text from cache if present
1361 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1362 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) ) );
1364 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1365 if ( $cacheHelpTimeout > 0 ) {
1366 $cached = $wgMemc->get( $key );
1371 $retval = $this->reallyMakeHelpMsg();
1372 if ( $cacheHelpTimeout > 0 ) {
1373 $wgMemc->set( $key, $retval, $cacheHelpTimeout );
1380 * @deprecated since 1.25
1381 * @return mixed|string
1383 public function reallyMakeHelpMsg() {
1384 wfDeprecated( __METHOD__
, '1.25' );
1387 // Use parent to make default message for the main module
1388 $msg = parent
::makeHelpMsg();
1390 $astriks = str_repeat( '*** ', 14 );
1391 $msg .= "\n\n$astriks Modules $astriks\n\n";
1393 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1394 $module = $this->mModuleMgr
->getModule( $name );
1395 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1397 $msg2 = $module->makeHelpMsg();
1398 if ( $msg2 !== false ) {
1404 $msg .= "\n$astriks Permissions $astriks\n\n";
1405 foreach ( self
::$mRights as $right => $rightMsg ) {
1406 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1407 ->useDatabase( false )
1408 ->inLanguage( 'en' )
1410 $groups = User
::getGroupsWithPermission( $right );
1411 $msg .= "* " . $right . " *\n $rightsMsg" .
1412 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1415 $msg .= "\n$astriks Formats $astriks\n\n";
1416 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1417 $module = $this->mModuleMgr
->getModule( $name );
1418 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1419 $msg2 = $module->makeHelpMsg();
1420 if ( $msg2 !== false ) {
1426 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1427 $credits = str_replace( "\n", "\n ", $credits );
1428 $msg .= "\n*** Credits: ***\n $credits\n";
1434 * @deprecated since 1.25
1435 * @param ApiBase $module
1436 * @param string $paramName What type of request is this? e.g. action,
1437 * query, list, prop, meta, format
1440 public static function makeHelpMsgHeader( $module, $paramName ) {
1441 wfDeprecated( __METHOD__
, '1.25' );
1442 $modulePrefix = $module->getModulePrefix();
1443 if ( strval( $modulePrefix ) !== '' ) {
1444 $modulePrefix = "($modulePrefix) ";
1447 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1451 * Check whether the user wants us to show version information in the API help
1453 * @deprecated since 1.21, always returns false
1455 public function getShowVersions() {
1456 wfDeprecated( __METHOD__
, '1.21' );
1462 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1463 * classes who wish to add their own modules to their lexicon or override the
1464 * behavior of inherent ones.
1466 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1467 * @param string $name The identifier for this module.
1468 * @param ApiBase $class The class where this module is implemented.
1470 protected function addModule( $name, $class ) {
1471 $this->getModuleManager()->addModule( $name, 'action', $class );
1475 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1476 * classes who wish to add to or modify current formatters.
1478 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1479 * @param string $name The identifier for this format.
1480 * @param ApiFormatBase $class The class implementing this format.
1482 protected function addFormat( $name, $class ) {
1483 $this->getModuleManager()->addModule( $name, 'format', $class );
1487 * Get the array mapping module names to class names
1488 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1491 function getModules() {
1492 return $this->getModuleManager()->getNamesWithClasses( 'action' );
1496 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1499 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1502 public function getFormats() {
1503 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1511 * This exception will be thrown when dieUsage is called to stop module execution.
1515 class UsageException
extends MWException
{
1522 private $mExtraData;
1525 * @param string $message
1526 * @param string $codestr
1528 * @param array|null $extradata
1530 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1531 parent
::__construct( $message, $code );
1532 $this->mCodestr
= $codestr;
1533 $this->mExtraData
= $extradata;
1539 public function getCodeString() {
1540 return $this->mCodestr
;
1546 public function getMessageArray() {
1548 'code' => $this->mCodestr
,
1549 'info' => $this->getMessage()
1551 if ( is_array( $this->mExtraData
) ) {
1552 $result = array_merge( $result, $this->mExtraData
);
1561 public function __toString() {
1562 return "{$this->getCodeString()}: {$this->getMessage()}";
1567 * For really cool vim folding this needs to be at the end:
1568 * vim: foldmarker=@{,@} foldmethod=marker