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',
69 'purge' => 'ApiPurge',
70 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
71 'rollback' => 'ApiRollback',
72 'delete' => 'ApiDelete',
73 'undelete' => 'ApiUndelete',
74 'protect' => 'ApiProtect',
75 'block' => 'ApiBlock',
76 'unblock' => 'ApiUnblock',
78 'edit' => 'ApiEditPage',
79 'upload' => 'ApiUpload',
80 'filerevert' => 'ApiFileRevert',
81 'emailuser' => 'ApiEmailUser',
82 'watch' => 'ApiWatch',
83 'patrol' => 'ApiPatrol',
84 'import' => 'ApiImport',
85 'clearhasmsg' => 'ApiClearHasMsg',
86 'userrights' => 'ApiUserrights',
87 'options' => 'ApiOptions',
88 'imagerotate' => 'ApiImageRotate',
89 'revisiondelete' => 'ApiRevisionDelete',
93 * List of available formats: format name => format class
95 private static $Formats = array(
96 'json' => 'ApiFormatJson',
97 'jsonfm' => 'ApiFormatJson',
98 'php' => 'ApiFormatPhp',
99 'phpfm' => 'ApiFormatPhp',
100 'wddx' => 'ApiFormatWddx',
101 'wddxfm' => 'ApiFormatWddx',
102 'xml' => 'ApiFormatXml',
103 'xmlfm' => 'ApiFormatXml',
104 'yaml' => 'ApiFormatYaml',
105 'yamlfm' => 'ApiFormatYaml',
106 'rawfm' => 'ApiFormatJson',
107 'txt' => 'ApiFormatTxt',
108 'txtfm' => 'ApiFormatTxt',
109 'dbg' => 'ApiFormatDbg',
110 'dbgfm' => 'ApiFormatDbg',
111 'dump' => 'ApiFormatDump',
112 'dumpfm' => 'ApiFormatDump',
113 'none' => 'ApiFormatNone',
116 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
118 * List of user roles that are specifically relevant to the API.
119 * array( 'right' => array ( 'msg' => 'Some message with a $1',
120 * 'params' => array ( $someVarToSubst ) ),
123 private static $mRights = array(
125 'msg' => 'right-writeapi',
128 'apihighlimits' => array(
129 'msg' => 'api-help-right-apihighlimits',
130 'params' => array( ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
)
133 // @codingStandardsIgnoreEnd
140 private $mModuleMgr, $mResult;
142 private $mEnableWrite;
143 private $mInternalMode, $mSquidMaxage, $mModule;
145 private $mCacheMode = 'private';
146 private $mCacheControl = array();
147 private $mParamsUsed = array();
150 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
152 * @param IContextSource|WebRequest $context If this is an instance of
153 * FauxRequest, errors are thrown and no printing occurs
154 * @param bool $enableWrite Should be set to true if the api may modify data
156 public function __construct( $context = null, $enableWrite = false ) {
157 if ( $context === null ) {
158 $context = RequestContext
::getMain();
159 } elseif ( $context instanceof WebRequest
) {
162 $context = RequestContext
::getMain();
164 // We set a derivative context so we can change stuff later
165 $this->setContext( new DerivativeContext( $context ) );
167 if ( isset( $request ) ) {
168 $this->getContext()->setRequest( $request );
171 $this->mInternalMode
= ( $this->getRequest() instanceof FauxRequest
);
173 // Special handling for the main module: $parent === $this
174 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
176 if ( !$this->mInternalMode
) {
177 // Impose module restrictions.
178 // If the current user cannot read,
179 // Remove all modules other than login
182 if ( $this->getVal( 'callback' ) !== null ) {
183 // JSON callback allows cross-site reads.
184 // For safety, strip user credentials.
185 wfDebug( "API: stripping user credentials for JSON callback\n" );
186 $wgUser = new User();
187 $this->getContext()->setUser( $wgUser );
191 $uselang = $this->getParameter( 'uselang' );
192 if ( $uselang === 'user' ) {
193 $uselang = $this->getUser()->getOption( 'language' );
194 $uselang = RequestContext
::sanitizeLangCode( $uselang );
195 Hooks
::run( 'UserGetLanguageObject', array( $this->getUser(), &$uselang, $this ) );
196 } elseif ( $uselang === 'content' ) {
198 $uselang = $wgContLang->getCode();
200 $code = RequestContext
::sanitizeLangCode( $uselang );
201 $this->getContext()->setLanguage( $code );
202 if ( !$this->mInternalMode
) {
204 $wgLang = $this->getContext()->getLanguage();
205 RequestContext
::getMain()->setLanguage( $wgLang );
208 $config = $this->getConfig();
209 $this->mModuleMgr
= new ApiModuleManager( $this );
210 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
211 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
212 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
213 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
215 $this->mResult
= new ApiResult( $this );
216 $this->mEnableWrite
= $enableWrite;
218 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
219 $this->mCommit
= false;
223 * Return true if the API was started by other PHP code using FauxRequest
226 public function isInternalMode() {
227 return $this->mInternalMode
;
231 * Get the ApiResult object associated with current request
235 public function getResult() {
236 return $this->mResult
;
240 * Get the API module object. Only works after executeAction()
244 public function getModule() {
245 return $this->mModule
;
249 * Get the result formatter object. Only works after setupExecuteAction()
251 * @return ApiFormatBase
253 public function getPrinter() {
254 return $this->mPrinter
;
258 * Set how long the response should be cached.
262 public function setCacheMaxAge( $maxage ) {
263 $this->setCacheControl( array(
264 'max-age' => $maxage,
265 's-maxage' => $maxage
270 * Set the type of caching headers which will be sent.
272 * @param string $mode One of:
273 * - 'public': Cache this object in public caches, if the maxage or smaxage
274 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
275 * not provided by any of these means, the object will be private.
276 * - 'private': Cache this object only in private client-side caches.
277 * - 'anon-public-user-private': Make this object cacheable for logged-out
278 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
279 * set consistently for a given URL, it cannot be set differently depending on
280 * things like the contents of the database, or whether the user is logged in.
282 * If the wiki does not allow anonymous users to read it, the mode set here
283 * will be ignored, and private caching headers will always be sent. In other words,
284 * the "public" mode is equivalent to saying that the data sent is as public as a page
287 * For user-dependent data, the private mode should generally be used. The
288 * anon-public-user-private mode should only be used where there is a particularly
289 * good performance reason for caching the anonymous response, but where the
290 * response to logged-in users may differ, or may contain private data.
292 * If this function is never called, then the default will be the private mode.
294 public function setCacheMode( $mode ) {
295 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
296 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
298 // Ignore for forwards-compatibility
302 if ( !User
::isEveryoneAllowed( 'read' ) ) {
303 // Private wiki, only private headers
304 if ( $mode !== 'private' ) {
305 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
311 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
312 // User language is used for i18n, so we don't want to publicly
313 // cache. Anons are ok, because if they have non-default language
314 // then there's an appropriate Vary header set by whatever set
315 // their non-default language.
316 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
317 "'anon-public-user-private' due to uselang=user\n" );
318 $mode = 'anon-public-user-private';
321 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
322 $this->mCacheMode
= $mode;
326 * Set directives (key/value pairs) for the Cache-Control header.
327 * Boolean values will be formatted as such, by including or omitting
328 * without an equals sign.
330 * Cache control values set here will only be used if the cache mode is not
331 * private, see setCacheMode().
333 * @param array $directives
335 public function setCacheControl( $directives ) {
336 $this->mCacheControl
= $directives +
$this->mCacheControl
;
340 * Create an instance of an output formatter by its name
342 * @param string $format
344 * @return ApiFormatBase
346 public function createPrinterByName( $format ) {
347 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
348 if ( $printer === null ) {
349 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
356 * Execute api request. Any errors will be handled if the API was called by the remote client.
358 public function execute() {
360 if ( $this->mInternalMode
) {
361 $this->executeAction();
363 $this->executeActionWithErrorHandling();
370 * Execute an action, and in case of an error, erase whatever partial results
371 * have been accumulated, and replace it with an error message and a help screen.
373 protected function executeActionWithErrorHandling() {
374 // Verify the CORS header before executing the action
375 if ( !$this->handleCORS() ) {
376 // handleCORS() has sent a 403, abort
380 // Exit here if the request method was OPTIONS
381 // (assume there will be a followup GET or POST)
382 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
386 // In case an error occurs during data output,
387 // clear the output buffer and print just the error information
390 $t = microtime( true );
392 $this->executeAction();
393 } catch ( Exception
$e ) {
394 $this->handleException( $e );
397 // Log the request whether or not there was an error
398 $this->logRequest( microtime( true ) - $t );
400 // Send cache headers after any code which might generate an error, to
401 // avoid sending public cache headers for errors.
402 $this->sendCacheHeaders();
408 * Handle an exception as an API response
411 * @param Exception $e
413 protected function handleException( Exception
$e ) {
414 // Bug 63145: Rollback any open database transactions
415 if ( !( $e instanceof UsageException
) ) {
416 // UsageExceptions are intentional, so don't rollback if that's the case
417 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
420 // Allow extra cleanup and logging
421 Hooks
::run( 'ApiMain::onException', array( $this, $e ) );
424 if ( !( $e instanceof UsageException
) ) {
425 MWExceptionHandler
::logException( $e );
428 // Handle any kind of exception by outputting properly formatted error message.
429 // If this fails, an unhandled exception should be thrown so that global error
430 // handler will process and log it.
432 $errCode = $this->substituteResultWithError( $e );
434 // Error results should not be cached
435 $this->setCacheMode( 'private' );
437 $response = $this->getRequest()->response();
438 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
439 if ( $e->getCode() === 0 ) {
440 $response->header( $headerStr );
442 $response->header( $headerStr, true, $e->getCode() );
445 // Reset and print just the error message
448 // If the error occurred during printing, do a printer->profileOut()
449 $this->mPrinter
->safeProfileOut();
450 $this->printResult( true );
454 * Handle an exception from the ApiBeforeMain hook.
456 * This tries to print the exception as an API response, to be more
457 * friendly to clients. If it fails, it will rethrow the exception.
460 * @param Exception $e
463 public static function handleApiBeforeMainException( Exception
$e ) {
467 $main = new self( RequestContext
::getMain(), false );
468 $main->handleException( $e );
469 } catch ( Exception
$e2 ) {
470 // Nope, even that didn't work. Punt.
474 // Log the request and reset cache headers
475 $main->logRequest( 0 );
476 $main->sendCacheHeaders();
482 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
484 * If no origin parameter is present, nothing happens.
485 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
486 * is set and false is returned.
487 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
488 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
491 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
493 protected function handleCORS() {
494 $originParam = $this->getParameter( 'origin' ); // defaults to null
495 if ( $originParam === null ) {
496 // No origin parameter, nothing to do
500 $request = $this->getRequest();
501 $response = $request->response();
502 // Origin: header is a space-separated list of origins, check all of them
503 $originHeader = $request->getHeader( 'Origin' );
504 if ( $originHeader === false ) {
507 $origins = explode( ' ', $originHeader );
510 if ( !in_array( $originParam, $origins ) ) {
511 // origin parameter set but incorrect
512 // Send a 403 response
513 $message = HttpStatus
::getMessage( 403 );
514 $response->header( "HTTP/1.1 403 $message", true, 403 );
515 $response->header( 'Cache-Control: no-cache' );
516 echo "'origin' parameter does not match Origin header\n";
521 $config = $this->getConfig();
522 $matchOrigin = self
::matchOrigin(
524 $config->get( 'CrossSiteAJAXdomains' ),
525 $config->get( 'CrossSiteAJAXdomainExceptions' )
528 if ( $matchOrigin ) {
529 $response->header( "Access-Control-Allow-Origin: $originParam" );
530 $response->header( 'Access-Control-Allow-Credentials: true' );
531 $response->header( 'Access-Control-Allow-Headers: Api-User-Agent' );
532 $this->getOutput()->addVaryHeader( 'Origin' );
539 * Attempt to match an Origin header against a set of rules and a set of exceptions
540 * @param string $value Origin header
541 * @param array $rules Set of wildcard rules
542 * @param array $exceptions Set of wildcard rules
543 * @return bool True if $value matches a rule in $rules and doesn't match
544 * any rules in $exceptions, false otherwise
546 protected static function matchOrigin( $value, $rules, $exceptions ) {
547 foreach ( $rules as $rule ) {
548 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
549 // Rule matches, check exceptions
550 foreach ( $exceptions as $exc ) {
551 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
564 * Helper function to convert wildcard string into a regex
568 * @param string $wildcard String with wildcards
569 * @return string Regular expression
571 protected static function wildcardToRegex( $wildcard ) {
572 $wildcard = preg_quote( $wildcard, '/' );
573 $wildcard = str_replace(
579 return "/^https?:\/\/$wildcard$/";
582 protected function sendCacheHeaders() {
583 $response = $this->getRequest()->response();
584 $out = $this->getOutput();
586 $config = $this->getConfig();
588 if ( $config->get( 'VaryOnXFP' ) ) {
589 $out->addVaryHeader( 'X-Forwarded-Proto' );
592 if ( $this->mCacheMode
== 'private' ) {
593 $response->header( 'Cache-Control: private' );
597 $useXVO = $config->get( 'UseXVO' );
598 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
599 $out->addVaryHeader( 'Cookie' );
600 $response->header( $out->getVaryHeader() );
602 $response->header( $out->getXVO() );
603 if ( $out->haveCacheVaryCookies() ) {
604 // Logged in, mark this request private
605 $response->header( 'Cache-Control: private' );
608 // Logged out, send normal public headers below
609 } elseif ( session_id() != '' ) {
610 // Logged in or otherwise has session (e.g. anonymous users who have edited)
611 // Mark request private
612 $response->header( 'Cache-Control: private' );
615 } // else no XVO and anonymous, send public headers below
618 // Send public headers
619 $response->header( $out->getVaryHeader() );
621 $response->header( $out->getXVO() );
624 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
625 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
626 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
628 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
629 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
632 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
633 // Public cache not requested
634 // Sending a Vary header in this case is harmless, and protects us
635 // against conditional calls of setCacheMaxAge().
636 $response->header( 'Cache-Control: private' );
641 $this->mCacheControl
['public'] = true;
643 // Send an Expires header
644 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
645 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
646 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
648 // Construct the Cache-Control header
651 foreach ( $this->mCacheControl
as $name => $value ) {
652 if ( is_bool( $value ) ) {
654 $ccHeader .= $separator . $name;
658 $ccHeader .= $separator . "$name=$value";
663 $response->header( "Cache-Control: $ccHeader" );
667 * Replace the result data with the information about an exception.
668 * Returns the error code
669 * @param Exception $e
672 protected function substituteResultWithError( $e ) {
673 $result = $this->getResult();
675 // Printer may not be initialized if the extractRequestParams() fails for the main module
676 if ( !isset( $this->mPrinter
) ) {
677 // The printer has not been created yet. Try to manually get formatter value.
678 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
679 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
680 $value = self
::API_DEFAULT_FORMAT
;
683 $this->mPrinter
= $this->createPrinterByName( $value );
686 // Printer may not be able to handle errors. This is particularly
687 // likely if the module returns something for getCustomPrinter().
688 if ( !$this->mPrinter
->canPrintErrors() ) {
689 $this->mPrinter
->safeProfileOut();
690 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
693 // Update raw mode flag for the selected printer.
694 $result->setRawMode( $this->mPrinter
->getNeedsRawData() );
696 $config = $this->getConfig();
698 if ( $e instanceof UsageException
) {
699 // User entered incorrect parameters - generate error response
700 $errMessage = $e->getMessageArray();
701 $link = wfExpandUrl( wfScript( 'api' ) );
702 ApiResult
::setContent( $errMessage, "See $link for API usage" );
704 // Something is seriously wrong
705 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
706 $info = 'Database query error';
708 $info = "Exception Caught: {$e->getMessage()}";
712 'code' => 'internal_api_error_' . get_class( $e ),
713 'info' => '[' . MWExceptionHandler
::getLogId( $e ) . '] ' . $info,
715 if ( $config->get( 'ShowExceptionDetails' ) ) {
716 ApiResult
::setContent(
718 MWExceptionHandler
::getRedactedTraceAsString( $e )
723 // Remember all the warnings to re-add them later
724 $oldResult = $result->getData();
725 $warnings = isset( $oldResult['warnings'] ) ?
$oldResult['warnings'] : null;
729 $requestid = $this->getParameter( 'requestid' );
730 if ( !is_null( $requestid ) ) {
731 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
733 if ( $config->get( 'ShowHostnames' ) ) {
734 // servedby is especially useful when debugging errors
735 $result->addValue( null, 'servedby', wfHostName(), ApiResult
::NO_SIZE_CHECK
);
737 if ( $warnings !== null ) {
738 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
741 $result->addValue( null, 'error', $errMessage, ApiResult
::NO_SIZE_CHECK
);
743 return $errMessage['code'];
747 * Set up for the execution.
750 protected function setupExecuteAction() {
751 // First add the id to the top element
752 $result = $this->getResult();
753 $requestid = $this->getParameter( 'requestid' );
754 if ( !is_null( $requestid ) ) {
755 $result->addValue( null, 'requestid', $requestid );
758 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
759 $servedby = $this->getParameter( 'servedby' );
761 $result->addValue( null, 'servedby', wfHostName() );
765 if ( $this->getParameter( 'curtimestamp' ) ) {
766 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
767 ApiResult
::NO_SIZE_CHECK
);
770 $params = $this->extractRequestParams();
772 $this->mAction
= $params['action'];
774 if ( !is_string( $this->mAction
) ) {
775 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
782 * Set up the module for response
783 * @return ApiBase The module that will handle this action
784 * @throws MWException
785 * @throws UsageException
787 protected function setupModule() {
788 // Instantiate the module requested by the user
789 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
790 if ( $module === null ) {
791 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
793 $moduleParams = $module->extractRequestParams();
795 // Check token, if necessary
796 if ( $module->needsToken() === true ) {
797 throw new MWException(
798 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
799 "See documentation for ApiBase::needsToken for details."
802 if ( $module->needsToken() ) {
803 if ( !$module->mustBePosted() ) {
804 throw new MWException(
805 "Module '{$module->getModuleName()}' must require POST to use tokens."
809 if ( !isset( $moduleParams['token'] ) ) {
810 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
813 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
815 $module->encodeParamName( 'token' ),
816 $this->getRequest()->getQueryValues()
820 "The '{$module->encodeParamName( 'token' )}' parameter was found in the query string, but must be in the POST body",
825 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
826 $this->dieUsageMsg( 'sessionfailure' );
834 * Check the max lag if necessary
835 * @param ApiBase $module Api module being used
836 * @param array $params Array an array containing the request parameters.
837 * @return bool True on success, false should exit immediately
839 protected function checkMaxLag( $module, $params ) {
840 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
842 $maxLag = $params['maxlag'];
843 list( $host, $lag ) = wfGetLB()->getMaxLag();
844 if ( $lag > $maxLag ) {
845 $response = $this->getRequest()->response();
847 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
848 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
850 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
851 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
854 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
862 * Check for sufficient permissions to execute
863 * @param ApiBase $module An Api module
865 protected function checkExecutePermissions( $module ) {
866 $user = $this->getUser();
867 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
868 !$user->isAllowed( 'read' )
870 $this->dieUsageMsg( 'readrequired' );
872 if ( $module->isWriteMode() ) {
873 if ( !$this->mEnableWrite
) {
874 $this->dieUsageMsg( 'writedisabled' );
876 if ( !$user->isAllowed( 'writeapi' ) ) {
877 $this->dieUsageMsg( 'writerequired' );
879 if ( wfReadOnly() ) {
880 $this->dieReadOnly();
884 // Allow extensions to stop execution for arbitrary reasons.
886 if ( !Hooks
::run( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
887 $this->dieUsageMsg( $message );
892 * Check asserts of the user's rights
893 * @param array $params
895 protected function checkAsserts( $params ) {
896 if ( isset( $params['assert'] ) ) {
897 $user = $this->getUser();
898 switch ( $params['assert'] ) {
900 if ( $user->isAnon() ) {
901 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
905 if ( !$user->isAllowed( 'bot' ) ) {
906 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
914 * Check POST for external response and setup result printer
915 * @param ApiBase $module An Api module
916 * @param array $params An array with the request parameters
918 protected function setupExternalResponse( $module, $params ) {
919 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
920 // Module requires POST. GET request might still be allowed
921 // if $wgDebugApi is true, otherwise fail.
922 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction
) );
925 // See if custom printer is used
926 $this->mPrinter
= $module->getCustomPrinter();
927 if ( is_null( $this->mPrinter
) ) {
928 // Create an appropriate printer
929 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
932 if ( $this->mPrinter
->getNeedsRawData() ) {
933 $this->getResult()->setRawMode();
938 * Execute the actual module, without any error handling
940 protected function executeAction() {
941 $params = $this->setupExecuteAction();
942 $module = $this->setupModule();
943 $this->mModule
= $module;
945 $this->checkExecutePermissions( $module );
947 if ( !$this->checkMaxLag( $module, $params ) ) {
951 if ( !$this->mInternalMode
) {
952 $this->setupExternalResponse( $module, $params );
955 $this->checkAsserts( $params );
958 $module->profileIn();
960 Hooks
::run( 'APIAfterExecute', array( &$module ) );
961 $module->profileOut();
963 $this->reportUnusedParams();
965 if ( !$this->mInternalMode
) {
966 //append Debug information
967 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
970 $this->printResult( false );
975 * Log the preceding request
976 * @param int $time Time in seconds
978 protected function logRequest( $time ) {
979 $request = $this->getRequest();
980 $milliseconds = $time === null ?
'?' : round( $time * 1000 );
982 ' ' . $request->getMethod() .
983 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
984 ' ' . $request->getIP() .
985 ' T=' . $milliseconds . 'ms';
986 foreach ( $this->getParamsUsed() as $name ) {
987 $value = $request->getVal( $name );
988 if ( $value === null ) {
991 $s .= ' ' . $name . '=';
992 if ( strlen( $value ) > 256 ) {
993 $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
994 $s .= $encValue . '[...]';
996 $s .= $this->encodeRequestLogValue( $value );
1000 wfDebugLog( 'api', $s, 'private' );
1004 * Encode a value in a format suitable for a space-separated log line.
1008 protected function encodeRequestLogValue( $s ) {
1011 $chars = ';@$!*(),/:';
1012 $numChars = strlen( $chars );
1013 for ( $i = 0; $i < $numChars; $i++
) {
1014 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1018 return strtr( rawurlencode( $s ), $table );
1022 * Get the request parameters used in the course of the preceding execute() request
1025 protected function getParamsUsed() {
1026 return array_keys( $this->mParamsUsed
);
1030 * Get a request value, and register the fact that it was used, for logging.
1031 * @param string $name
1032 * @param mixed $default
1035 public function getVal( $name, $default = null ) {
1036 $this->mParamsUsed
[$name] = true;
1038 $ret = $this->getRequest()->getVal( $name );
1039 if ( $ret === null ) {
1040 if ( $this->getRequest()->getArray( $name ) !== null ) {
1041 // See bug 10262 for why we don't just join( '|', ... ) the
1044 "Parameter '$name' uses unsupported PHP array syntax"
1053 * Get a boolean request value, and register the fact that the parameter
1054 * was used, for logging.
1055 * @param string $name
1058 public function getCheck( $name ) {
1059 return $this->getVal( $name, null ) !== null;
1063 * Get a request upload, and register the fact that it was used, for logging.
1066 * @param string $name Parameter name
1067 * @return WebRequestUpload
1069 public function getUpload( $name ) {
1070 $this->mParamsUsed
[$name] = true;
1072 return $this->getRequest()->getUpload( $name );
1076 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1077 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1079 protected function reportUnusedParams() {
1080 $paramsUsed = $this->getParamsUsed();
1081 $allParams = $this->getRequest()->getValueNames();
1083 if ( !$this->mInternalMode
) {
1084 // Printer has not yet executed; don't warn that its parameters are unused
1085 $printerParams = array_map(
1086 array( $this->mPrinter
, 'encodeParamName' ),
1087 array_keys( $this->mPrinter
->getFinalParams() ?
: array() )
1089 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1091 $unusedParams = array_diff( $allParams, $paramsUsed );
1094 if ( count( $unusedParams ) ) {
1095 $s = count( $unusedParams ) > 1 ?
's' : '';
1096 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1101 * Print results using the current printer
1103 * @param bool $isError
1105 protected function printResult( $isError ) {
1106 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1107 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1110 $this->getResult()->cleanUpUTF8();
1111 $printer = $this->mPrinter
;
1112 $printer->profileIn();
1114 $printer->initPrinter( false );
1116 $printer->execute();
1117 $printer->closePrinter();
1118 $printer->profileOut();
1124 public function isReadMode() {
1129 * See ApiBase for description.
1133 public function getAllowedParams() {
1136 ApiBase
::PARAM_DFLT
=> 'help',
1137 ApiBase
::PARAM_TYPE
=> 'submodule',
1140 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1141 ApiBase
::PARAM_TYPE
=> 'submodule',
1144 ApiBase
::PARAM_TYPE
=> 'integer'
1147 ApiBase
::PARAM_TYPE
=> 'integer',
1148 ApiBase
::PARAM_DFLT
=> 0
1151 ApiBase
::PARAM_TYPE
=> 'integer',
1152 ApiBase
::PARAM_DFLT
=> 0
1155 ApiBase
::PARAM_TYPE
=> array( 'user', 'bot' )
1157 'requestid' => null,
1158 'servedby' => false,
1159 'curtimestamp' => false,
1162 ApiBase
::PARAM_DFLT
=> 'user',
1167 /** @see ApiBase::getExamplesMessages() */
1168 protected function getExamplesMessages() {
1171 => 'apihelp-help-example-main',
1172 'action=help&recursivesubmodules=1'
1173 => 'apihelp-help-example-recursive',
1177 public function modifyHelp( array &$help, array $options ) {
1178 // Wish PHP had an "array_insert_before". Instead, we have to manually
1179 // reindex the array to get 'permissions' in the right place.
1182 foreach ( $oldHelp as $k => $v ) {
1183 if ( $k === 'submodules' ) {
1184 $help['permissions'] = '';
1188 $help['credits'] = '';
1190 // Fill 'permissions'
1191 $help['permissions'] .= Html
::openElement( 'div',
1192 array( 'class' => 'apihelp-block apihelp-permissions' ) );
1193 $m = $this->msg( 'api-help-permissions' );
1194 if ( !$m->isDisabled() ) {
1195 $help['permissions'] .= Html
::rawElement( 'div', array( 'class' => 'apihelp-block-head' ),
1196 $m->numParams( count( self
::$mRights ) )->parse()
1199 $help['permissions'] .= Html
::openElement( 'dl' );
1200 foreach ( self
::$mRights as $right => $rightMsg ) {
1201 $help['permissions'] .= Html
::element( 'dt', null, $right );
1203 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1204 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1206 $groups = array_map( function ( $group ) {
1207 return $group == '*' ?
'all' : $group;
1208 }, User
::getGroupsWithPermission( $right ) );
1210 $help['permissions'] .= Html
::rawElement( 'dd', null,
1211 $this->msg( 'api-help-permissions-granted-to' )
1212 ->numParams( count( $groups ) )
1213 ->params( $this->getLanguage()->commaList( $groups ) )
1217 $help['permissions'] .= Html
::closeElement( 'dl' );
1218 $help['permissions'] .= Html
::closeElement( 'div' );
1220 // Fill 'credits', if applicable
1221 if ( empty( $options['nolead'] ) ) {
1222 $help['credits'] .= Html
::element( 'h' . min( 6, $options['headerlevel'] +
1 ),
1223 array( 'id' => '+credits', 'class' => 'apihelp-header' ),
1224 $this->msg( 'api-credits-header' )->parse()
1226 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1230 private $mCanApiHighLimits = null;
1233 * Check whether the current user is allowed to use high limits
1236 public function canApiHighLimits() {
1237 if ( !isset( $this->mCanApiHighLimits
) ) {
1238 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1241 return $this->mCanApiHighLimits
;
1245 * Overrides to return this instance's module manager.
1246 * @return ApiModuleManager
1248 public function getModuleManager() {
1249 return $this->mModuleMgr
;
1253 * Fetches the user agent used for this request
1255 * The value will be the combination of the 'Api-User-Agent' header (if
1256 * any) and the standard User-Agent header (if any).
1260 public function getUserAgent() {
1262 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1263 $this->getRequest()->getHeader( 'User-agent' )
1267 /************************************************************************//**
1273 * Sets whether the pretty-printer should format *bold* and $italics$
1275 * @deprecated since 1.25
1278 public function setHelp( $help = true ) {
1279 wfDeprecated( __METHOD__
, '1.25' );
1280 $this->mPrinter
->setHelp( $help );
1284 * Override the parent to generate help messages for all available modules.
1286 * @deprecated since 1.25
1289 public function makeHelpMsg() {
1290 wfDeprecated( __METHOD__
, '1.25' );
1293 // Get help text from cache if present
1294 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1295 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) ) );
1297 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1298 if ( $cacheHelpTimeout > 0 ) {
1299 $cached = $wgMemc->get( $key );
1304 $retval = $this->reallyMakeHelpMsg();
1305 if ( $cacheHelpTimeout > 0 ) {
1306 $wgMemc->set( $key, $retval, $cacheHelpTimeout );
1313 * @deprecated since 1.25
1314 * @return mixed|string
1316 public function reallyMakeHelpMsg() {
1317 wfDeprecated( __METHOD__
, '1.25' );
1320 // Use parent to make default message for the main module
1321 $msg = parent
::makeHelpMsg();
1323 $astriks = str_repeat( '*** ', 14 );
1324 $msg .= "\n\n$astriks Modules $astriks\n\n";
1326 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1327 $module = $this->mModuleMgr
->getModule( $name );
1328 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1330 $msg2 = $module->makeHelpMsg();
1331 if ( $msg2 !== false ) {
1337 $msg .= "\n$astriks Permissions $astriks\n\n";
1338 foreach ( self
::$mRights as $right => $rightMsg ) {
1339 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1340 ->useDatabase( false )
1341 ->inLanguage( 'en' )
1343 $groups = User
::getGroupsWithPermission( $right );
1344 $msg .= "* " . $right . " *\n $rightsMsg" .
1345 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1348 $msg .= "\n$astriks Formats $astriks\n\n";
1349 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1350 $module = $this->mModuleMgr
->getModule( $name );
1351 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1352 $msg2 = $module->makeHelpMsg();
1353 if ( $msg2 !== false ) {
1359 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1360 $credits = str_replace( "\n", "\n ", $credits );
1361 $msg .= "\n*** Credits: ***\n $credits\n";
1367 * @deprecated since 1.25
1368 * @param ApiBase $module
1369 * @param string $paramName What type of request is this? e.g. action,
1370 * query, list, prop, meta, format
1373 public static function makeHelpMsgHeader( $module, $paramName ) {
1374 wfDeprecated( __METHOD__
, '1.25' );
1375 $modulePrefix = $module->getModulePrefix();
1376 if ( strval( $modulePrefix ) !== '' ) {
1377 $modulePrefix = "($modulePrefix) ";
1380 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1384 * Check whether the user wants us to show version information in the API help
1386 * @deprecated since 1.21, always returns false
1388 public function getShowVersions() {
1389 wfDeprecated( __METHOD__
, '1.21' );
1395 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1396 * classes who wish to add their own modules to their lexicon or override the
1397 * behavior of inherent ones.
1399 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1400 * @param string $name The identifier for this module.
1401 * @param ApiBase $class The class where this module is implemented.
1403 protected function addModule( $name, $class ) {
1404 $this->getModuleManager()->addModule( $name, 'action', $class );
1408 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1409 * classes who wish to add to or modify current formatters.
1411 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1412 * @param string $name The identifier for this format.
1413 * @param ApiFormatBase $class The class implementing this format.
1415 protected function addFormat( $name, $class ) {
1416 $this->getModuleManager()->addModule( $name, 'format', $class );
1420 * Get the array mapping module names to class names
1421 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1424 function getModules() {
1425 return $this->getModuleManager()->getNamesWithClasses( 'action' );
1429 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1432 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1435 public function getFormats() {
1436 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1444 * This exception will be thrown when dieUsage is called to stop module execution.
1448 class UsageException
extends MWException
{
1455 private $mExtraData;
1458 * @param string $message
1459 * @param string $codestr
1461 * @param array|null $extradata
1463 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1464 parent
::__construct( $message, $code );
1465 $this->mCodestr
= $codestr;
1466 $this->mExtraData
= $extradata;
1472 public function getCodeString() {
1473 return $this->mCodestr
;
1479 public function getMessageArray() {
1481 'code' => $this->mCodestr
,
1482 'info' => $this->getMessage()
1484 if ( is_array( $this->mExtraData
) ) {
1485 $result = array_merge( $result, $this->mExtraData
);
1494 public function __toString() {
1495 return "{$this->getCodeString()}: {$this->getMessage()}";
1500 * For really cool vim folding this needs to be at the end:
1501 * vim: foldmarker=@{,@} foldmethod=marker