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
= 'xmlfm';
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 'runjobs' => 'ApiRunJobs',
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 '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' => 'Use of the write API',
127 'apihighlimits' => array(
128 'msg' => 'Use higher limits in API queries (Slow queries: $1 results; Fast queries: $2 results). The limits for slow queries also apply to multivalue parameters.',
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 $context IContextSource|WebRequest - 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 global $wgAPIModules, $wgAPIFormatModules;
191 $this->mModuleMgr
= new ApiModuleManager( $this );
192 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
193 $this->mModuleMgr
->addModules( $wgAPIModules, 'action' );
194 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
195 $this->mModuleMgr
->addModules( $wgAPIFormatModules, 'format' );
197 $this->mResult
= new ApiResult( $this );
198 $this->mEnableWrite
= $enableWrite;
200 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
201 $this->mCommit
= false;
205 * Return true if the API was started by other PHP code using FauxRequest
208 public function isInternalMode() {
209 return $this->mInternalMode
;
213 * Get the ApiResult object associated with current request
217 public function getResult() {
218 return $this->mResult
;
222 * Get the API module object. Only works after executeAction()
226 public function getModule() {
227 return $this->mModule
;
231 * Get the result formatter object. Only works after setupExecuteAction()
233 * @return ApiFormatBase
235 public function getPrinter() {
236 return $this->mPrinter
;
240 * Set how long the response should be cached.
244 public function setCacheMaxAge( $maxage ) {
245 $this->setCacheControl( array(
246 'max-age' => $maxage,
247 's-maxage' => $maxage
252 * Set the type of caching headers which will be sent.
254 * @param string $mode One of:
255 * - 'public': Cache this object in public caches, if the maxage or smaxage
256 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
257 * not provided by any of these means, the object will be private.
258 * - 'private': Cache this object only in private client-side caches.
259 * - 'anon-public-user-private': Make this object cacheable for logged-out
260 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
261 * set consistently for a given URL, it cannot be set differently depending on
262 * things like the contents of the database, or whether the user is logged in.
264 * If the wiki does not allow anonymous users to read it, the mode set here
265 * will be ignored, and private caching headers will always be sent. In other words,
266 * the "public" mode is equivalent to saying that the data sent is as public as a page
269 * For user-dependent data, the private mode should generally be used. The
270 * anon-public-user-private mode should only be used where there is a particularly
271 * good performance reason for caching the anonymous response, but where the
272 * response to logged-in users may differ, or may contain private data.
274 * If this function is never called, then the default will be the private mode.
276 public function setCacheMode( $mode ) {
277 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
278 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
280 // Ignore for forwards-compatibility
284 if ( !User
::isEveryoneAllowed( 'read' ) ) {
285 // Private wiki, only private headers
286 if ( $mode !== 'private' ) {
287 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
293 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
294 $this->mCacheMode
= $mode;
298 * Set directives (key/value pairs) for the Cache-Control header.
299 * Boolean values will be formatted as such, by including or omitting
300 * without an equals sign.
302 * Cache control values set here will only be used if the cache mode is not
303 * private, see setCacheMode().
305 * @param $directives array
307 public function setCacheControl( $directives ) {
308 $this->mCacheControl
= $directives +
$this->mCacheControl
;
312 * Create an instance of an output formatter by its name
314 * @param $format string
316 * @return ApiFormatBase
318 public function createPrinterByName( $format ) {
319 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
320 if ( $printer === null ) {
321 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
328 * Execute api request. Any errors will be handled if the API was called by the remote client.
330 public function execute() {
332 if ( $this->mInternalMode
) {
333 $this->executeAction();
335 $this->executeActionWithErrorHandling();
342 * Execute an action, and in case of an error, erase whatever partial results
343 * have been accumulated, and replace it with an error message and a help screen.
345 protected function executeActionWithErrorHandling() {
346 // Verify the CORS header before executing the action
347 if ( !$this->handleCORS() ) {
348 // handleCORS() has sent a 403, abort
352 // Exit here if the request method was OPTIONS
353 // (assume there will be a followup GET or POST)
354 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
358 // In case an error occurs during data output,
359 // clear the output buffer and print just the error information
362 $t = microtime( true );
364 $this->executeAction();
365 } catch ( Exception
$e ) {
366 $this->handleException( $e );
369 // Log the request whether or not there was an error
370 $this->logRequest( microtime( true ) - $t );
372 // Send cache headers after any code which might generate an error, to
373 // avoid sending public cache headers for errors.
374 $this->sendCacheHeaders();
376 if ( $this->mPrinter
->getIsHtml() && !$this->mPrinter
->isDisabled() ) {
384 * Handle an exception as an API response
387 * @param Exception $e
389 protected function handleException( Exception
$e ) {
390 // Allow extra cleanup and logging
391 wfRunHooks( 'ApiMain::onException', array( $this, $e ) );
394 if ( !( $e instanceof UsageException
) ) {
395 MWExceptionHandler
::logException( $e );
398 // Handle any kind of exception by outputting properly formatted error message.
399 // If this fails, an unhandled exception should be thrown so that global error
400 // handler will process and log it.
402 $errCode = $this->substituteResultWithError( $e );
404 // Error results should not be cached
405 $this->setCacheMode( 'private' );
407 $response = $this->getRequest()->response();
408 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
409 if ( $e->getCode() === 0 ) {
410 $response->header( $headerStr );
412 $response->header( $headerStr, true, $e->getCode() );
415 // Reset and print just the error message
418 // If the error occurred during printing, do a printer->profileOut()
419 $this->mPrinter
->safeProfileOut();
420 $this->printResult( true );
424 * Handle an exception from the ApiBeforeMain hook.
426 * This tries to print the exception as an API response, to be more
427 * friendly to clients. If it fails, it will rethrow the exception.
430 * @param Exception $e
432 public static function handleApiBeforeMainException( Exception
$e ) {
436 $main = new self( RequestContext
::getMain(), false );
437 $main->handleException( $e );
438 } catch ( Exception
$e2 ) {
439 // Nope, even that didn't work. Punt.
443 // Log the request and reset cache headers
444 $main->logRequest( 0 );
445 $main->sendCacheHeaders();
451 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
453 * If no origin parameter is present, nothing happens.
454 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
455 * is set and false is returned.
456 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
457 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
460 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
462 protected function handleCORS() {
463 global $wgCrossSiteAJAXdomains, $wgCrossSiteAJAXdomainExceptions;
465 $originParam = $this->getParameter( 'origin' ); // defaults to null
466 if ( $originParam === null ) {
467 // No origin parameter, nothing to do
471 $request = $this->getRequest();
472 $response = $request->response();
473 // Origin: header is a space-separated list of origins, check all of them
474 $originHeader = $request->getHeader( 'Origin' );
475 if ( $originHeader === false ) {
478 $origins = explode( ' ', $originHeader );
481 if ( !in_array( $originParam, $origins ) ) {
482 // origin parameter set but incorrect
483 // Send a 403 response
484 $message = HttpStatus
::getMessage( 403 );
485 $response->header( "HTTP/1.1 403 $message", true, 403 );
486 $response->header( 'Cache-Control: no-cache' );
487 echo "'origin' parameter does not match Origin header\n";
492 $matchOrigin = self
::matchOrigin(
494 $wgCrossSiteAJAXdomains,
495 $wgCrossSiteAJAXdomainExceptions
498 if ( $matchOrigin ) {
499 $response->header( "Access-Control-Allow-Origin: $originParam" );
500 $response->header( 'Access-Control-Allow-Credentials: true' );
501 $this->getOutput()->addVaryHeader( 'Origin' );
508 * Attempt to match an Origin header against a set of rules and a set of exceptions
509 * @param string $value Origin header
510 * @param array $rules Set of wildcard rules
511 * @param array $exceptions Set of wildcard rules
512 * @return bool True if $value matches a rule in $rules and doesn't match
513 * any rules in $exceptions, false otherwise
515 protected static function matchOrigin( $value, $rules, $exceptions ) {
516 foreach ( $rules as $rule ) {
517 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
518 // Rule matches, check exceptions
519 foreach ( $exceptions as $exc ) {
520 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
533 * Helper function to convert wildcard string into a regex
537 * @param string $wildcard String with wildcards
538 * @return string Regular expression
540 protected static function wildcardToRegex( $wildcard ) {
541 $wildcard = preg_quote( $wildcard, '/' );
542 $wildcard = str_replace(
548 return "/https?:\/\/$wildcard/";
551 protected function sendCacheHeaders() {
552 global $wgUseXVO, $wgVaryOnXFP;
553 $response = $this->getRequest()->response();
554 $out = $this->getOutput();
556 if ( $wgVaryOnXFP ) {
557 $out->addVaryHeader( 'X-Forwarded-Proto' );
560 if ( $this->mCacheMode
== 'private' ) {
561 $response->header( 'Cache-Control: private' );
566 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
567 $out->addVaryHeader( 'Cookie' );
568 $response->header( $out->getVaryHeader() );
570 $response->header( $out->getXVO() );
571 if ( $out->haveCacheVaryCookies() ) {
572 // Logged in, mark this request private
573 $response->header( 'Cache-Control: private' );
577 // Logged out, send normal public headers below
578 } elseif ( session_id() != '' ) {
579 // Logged in or otherwise has session (e.g. anonymous users who have edited)
580 // Mark request private
581 $response->header( 'Cache-Control: private' );
584 } // else no XVO and anonymous, send public headers below
587 // Send public headers
588 $response->header( $out->getVaryHeader() );
590 $response->header( $out->getXVO() );
593 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
594 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
595 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
597 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
598 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
601 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
602 // Public cache not requested
603 // Sending a Vary header in this case is harmless, and protects us
604 // against conditional calls of setCacheMaxAge().
605 $response->header( 'Cache-Control: private' );
610 $this->mCacheControl
['public'] = true;
612 // Send an Expires header
613 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
614 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
615 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
617 // Construct the Cache-Control header
620 foreach ( $this->mCacheControl
as $name => $value ) {
621 if ( is_bool( $value ) ) {
623 $ccHeader .= $separator . $name;
627 $ccHeader .= $separator . "$name=$value";
632 $response->header( "Cache-Control: $ccHeader" );
636 * Replace the result data with the information about an exception.
637 * Returns the error code
638 * @param $e Exception
641 protected function substituteResultWithError( $e ) {
642 global $wgShowHostnames;
644 $result = $this->getResult();
645 // Printer may not be initialized if the extractRequestParams() fails for the main module
646 if ( !isset( $this->mPrinter
) ) {
647 // The printer has not been created yet. Try to manually get formatter value.
648 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
649 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
650 $value = self
::API_DEFAULT_FORMAT
;
653 $this->mPrinter
= $this->createPrinterByName( $value );
654 if ( $this->mPrinter
->getNeedsRawData() ) {
655 $result->setRawMode();
659 if ( $e instanceof UsageException
) {
660 // User entered incorrect parameters - print usage screen
661 $errMessage = $e->getMessageArray();
663 // Only print the help message when this is for the developer, not runtime
664 if ( $this->mPrinter
->getWantsHelp() ||
$this->mAction
== 'help' ) {
665 ApiResult
::setContent( $errMessage, $this->makeHelpMsg() );
668 global $wgShowSQLErrors, $wgShowExceptionDetails;
669 // Something is seriously wrong
670 if ( ( $e instanceof DBQueryError
) && !$wgShowSQLErrors ) {
671 $info = 'Database query error';
673 $info = "Exception Caught: {$e->getMessage()}";
677 'code' => 'internal_api_error_' . get_class( $e ),
680 ApiResult
::setContent(
682 $wgShowExceptionDetails ?
"\n\n{$e->getTraceAsString()}\n\n" : ''
686 // Remember all the warnings to re-add them later
687 $oldResult = $result->getData();
688 $warnings = isset( $oldResult['warnings'] ) ?
$oldResult['warnings'] : null;
691 $result->disableSizeCheck();
693 $requestid = $this->getParameter( 'requestid' );
694 if ( !is_null( $requestid ) ) {
695 $result->addValue( null, 'requestid', $requestid );
697 if ( $wgShowHostnames ) {
698 // servedby is especially useful when debugging errors
699 $result->addValue( null, 'servedby', wfHostName() );
701 if ( $warnings !== null ) {
702 $result->addValue( null, 'warnings', $warnings );
705 $result->addValue( null, 'error', $errMessage );
707 return $errMessage['code'];
711 * Set up for the execution.
714 protected function setupExecuteAction() {
715 global $wgShowHostnames;
717 // First add the id to the top element
718 $result = $this->getResult();
719 $requestid = $this->getParameter( 'requestid' );
720 if ( !is_null( $requestid ) ) {
721 $result->addValue( null, 'requestid', $requestid );
724 if ( $wgShowHostnames ) {
725 $servedby = $this->getParameter( 'servedby' );
727 $result->addValue( null, 'servedby', wfHostName() );
731 $params = $this->extractRequestParams();
733 $this->mAction
= $params['action'];
735 if ( !is_string( $this->mAction
) ) {
736 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
743 * Set up the module for response
744 * @return ApiBase The module that will handle this action
746 protected function setupModule() {
747 // Instantiate the module requested by the user
748 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
749 if ( $module === null ) {
750 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
752 $moduleParams = $module->extractRequestParams();
754 // Die if token required, but not provided
755 $salt = $module->getTokenSalt();
756 if ( $salt !== false ) {
757 if ( !isset( $moduleParams['token'] ) ) {
758 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
761 if ( !$this->getUser()->matchEditToken(
762 $moduleParams['token'],
764 $this->getContext()->getRequest() )
766 $this->dieUsageMsg( 'sessionfailure' );
774 * Check the max lag if necessary
775 * @param $module ApiBase object: Api module being used
776 * @param array $params an array containing the request parameters.
777 * @return boolean True on success, false should exit immediately
779 protected function checkMaxLag( $module, $params ) {
780 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
782 global $wgShowHostnames;
783 $maxLag = $params['maxlag'];
784 list( $host, $lag ) = wfGetLB()->getMaxLag();
785 if ( $lag > $maxLag ) {
786 $response = $this->getRequest()->response();
788 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
789 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
791 if ( $wgShowHostnames ) {
792 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
795 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
803 * Check for sufficient permissions to execute
804 * @param $module ApiBase An Api module
806 protected function checkExecutePermissions( $module ) {
807 $user = $this->getUser();
808 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
809 !$user->isAllowed( 'read' )
811 $this->dieUsageMsg( 'readrequired' );
813 if ( $module->isWriteMode() ) {
814 if ( !$this->mEnableWrite
) {
815 $this->dieUsageMsg( 'writedisabled' );
817 if ( !$user->isAllowed( 'writeapi' ) ) {
818 $this->dieUsageMsg( 'writerequired' );
820 if ( wfReadOnly() ) {
821 $this->dieReadOnly();
825 // Allow extensions to stop execution for arbitrary reasons.
827 if ( !wfRunHooks( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
828 $this->dieUsageMsg( $message );
833 * Check asserts of the user's rights
834 * @param $params array
836 protected function checkAsserts( $params ) {
837 if ( isset( $params['assert'] ) ) {
838 $user = $this->getUser();
839 switch ( $params['assert'] ) {
841 if ( $user->isAnon() ) {
842 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
846 if ( !$user->isAllowed( 'bot' ) ) {
847 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
855 * Check POST for external response and setup result printer
856 * @param $module ApiBase An Api module
857 * @param array $params an array with the request parameters
859 protected function setupExternalResponse( $module, $params ) {
860 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
861 // Module requires POST. GET request might still be allowed
862 // if $wgDebugApi is true, otherwise fail.
863 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction
) );
866 // See if custom printer is used
867 $this->mPrinter
= $module->getCustomPrinter();
868 if ( is_null( $this->mPrinter
) ) {
869 // Create an appropriate printer
870 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
873 if ( $this->mPrinter
->getNeedsRawData() ) {
874 $this->getResult()->setRawMode();
879 * Execute the actual module, without any error handling
881 protected function executeAction() {
882 $params = $this->setupExecuteAction();
883 $module = $this->setupModule();
884 $this->mModule
= $module;
886 $this->checkExecutePermissions( $module );
888 if ( !$this->checkMaxLag( $module, $params ) ) {
892 if ( !$this->mInternalMode
) {
893 $this->setupExternalResponse( $module, $params );
896 $this->checkAsserts( $params );
899 $module->profileIn();
901 wfRunHooks( 'APIAfterExecute', array( &$module ) );
902 $module->profileOut();
904 $this->reportUnusedParams();
906 if ( !$this->mInternalMode
) {
907 //append Debug information
908 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
911 $this->printResult( false );
916 * Log the preceding request
917 * @param int $time Time in seconds
919 protected function logRequest( $time ) {
920 $request = $this->getRequest();
921 $milliseconds = $time === null ?
'?' : round( $time * 1000 );
923 ' ' . $request->getMethod() .
924 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
925 ' ' . $request->getIP() .
926 ' T=' . $milliseconds . 'ms';
927 foreach ( $this->getParamsUsed() as $name ) {
928 $value = $request->getVal( $name );
929 if ( $value === null ) {
932 $s .= ' ' . $name . '=';
933 if ( strlen( $value ) > 256 ) {
934 $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
935 $s .= $encValue . '[...]';
937 $s .= $this->encodeRequestLogValue( $value );
941 wfDebugLog( 'api', $s, 'private' );
945 * Encode a value in a format suitable for a space-separated log line.
947 protected function encodeRequestLogValue( $s ) {
950 $chars = ';@$!*(),/:';
951 $numChars = strlen( $chars );
952 for ( $i = 0; $i < $numChars; $i++
) {
953 $table[rawurlencode( $chars[$i] )] = $chars[$i];
957 return strtr( rawurlencode( $s ), $table );
961 * Get the request parameters used in the course of the preceding execute() request
963 protected function getParamsUsed() {
964 return array_keys( $this->mParamsUsed
);
968 * Get a request value, and register the fact that it was used, for logging.
970 public function getVal( $name, $default = null ) {
971 $this->mParamsUsed
[$name] = true;
973 return $this->getRequest()->getVal( $name, $default );
977 * Get a boolean request value, and register the fact that the parameter
978 * was used, for logging.
980 public function getCheck( $name ) {
981 $this->mParamsUsed
[$name] = true;
983 return $this->getRequest()->getCheck( $name );
987 * Get a request upload, and register the fact that it was used, for logging.
990 * @param string $name Parameter name
991 * @return WebRequestUpload
993 public function getUpload( $name ) {
994 $this->mParamsUsed
[$name] = true;
996 return $this->getRequest()->getUpload( $name );
1000 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1001 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1003 protected function reportUnusedParams() {
1004 $paramsUsed = $this->getParamsUsed();
1005 $allParams = $this->getRequest()->getValueNames();
1007 if ( !$this->mInternalMode
) {
1008 // Printer has not yet executed; don't warn that its parameters are unused
1009 $printerParams = array_map(
1010 array( $this->mPrinter
, 'encodeParamName' ),
1011 array_keys( $this->mPrinter
->getFinalParams() ?
: array() )
1013 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1015 $unusedParams = array_diff( $allParams, $paramsUsed );
1018 if ( count( $unusedParams ) ) {
1019 $s = count( $unusedParams ) > 1 ?
's' : '';
1020 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1025 * Print results using the current printer
1027 * @param $isError bool
1029 protected function printResult( $isError ) {
1031 if ( $wgDebugAPI !== false ) {
1032 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1035 $this->getResult()->cleanUpUTF8();
1036 $printer = $this->mPrinter
;
1037 $printer->profileIn();
1040 * If the help message is requested in the default (xmlfm) format,
1041 * tell the printer not to escape ampersands so that our links do
1044 $isHelp = $isError ||
$this->mAction
== 'help';
1045 $printer->setUnescapeAmps( $isHelp && $printer->getFormat() == 'XML' && $printer->getIsHtml() );
1047 $printer->initPrinter( $isHelp );
1049 $printer->execute();
1050 $printer->closePrinter();
1051 $printer->profileOut();
1057 public function isReadMode() {
1062 * See ApiBase for description.
1066 public function getAllowedParams() {
1069 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1070 ApiBase
::PARAM_TYPE
=> $this->mModuleMgr
->getNames( 'format' )
1073 ApiBase
::PARAM_DFLT
=> 'help',
1074 ApiBase
::PARAM_TYPE
=> $this->mModuleMgr
->getNames( 'action' )
1077 ApiBase
::PARAM_TYPE
=> 'integer'
1080 ApiBase
::PARAM_TYPE
=> 'integer',
1081 ApiBase
::PARAM_DFLT
=> 0
1084 ApiBase
::PARAM_TYPE
=> 'integer',
1085 ApiBase
::PARAM_DFLT
=> 0
1088 ApiBase
::PARAM_TYPE
=> array( 'user', 'bot' )
1090 'requestid' => null,
1091 'servedby' => false,
1097 * See ApiBase for description.
1101 public function getParamDescription() {
1103 'format' => 'The format of the output',
1104 'action' => 'What action you would like to perform. See below for module help',
1106 'Maximum lag can be used when MediaWiki is installed on a database replicated cluster.',
1107 'To save actions causing any more site replication lag, this parameter can make the client',
1108 'wait until the replication lag is less than the specified value.',
1109 'In case of a replag error, error code "maxlag" is returned, with the message like',
1110 '"Waiting for $host: $lag seconds lagged\n".',
1111 'See https://www.mediawiki.org/wiki/Manual:Maxlag_parameter for more information',
1113 'smaxage' => 'Set the s-maxage header to this many seconds. Errors are never cached',
1114 'maxage' => 'Set the max-age header to this many seconds. Errors are never cached',
1115 'assert' => 'Verify the user is logged in if set to "user", or has the bot userright if "bot"',
1116 'requestid' => 'Request ID to distinguish requests. This will just be output back to you',
1117 'servedby' => 'Include the hostname that served the request in the ' .
1118 'results. Unconditionally shown on error',
1120 'When accessing the API using a cross-domain AJAX request (CORS), set this to the',
1121 'originating domain. This must be included in any pre-flight request, and',
1122 'therefore must be part of the request URI (not the POST body). This must match',
1123 'one of the origins in the Origin: header exactly, so it has to be set to ',
1124 'something like http://en.wikipedia.org or https://meta.wikimedia.org . If this',
1125 'parameter does not match the Origin: header, a 403 response will be returned. If',
1126 'this parameter matches the Origin: header and the origin is whitelisted, an',
1127 'Access-Control-Allow-Origin header will be set.',
1133 * See ApiBase for description.
1137 public function getDescription() {
1141 '**********************************************************************************************',
1143 '** This is an auto-generated MediaWiki API documentation page **',
1145 '** Documentation and Examples: **',
1146 '** https://www.mediawiki.org/wiki/API **',
1148 '**********************************************************************************************',
1150 'Status: All features shown on this page should be working, but the API',
1151 ' is still in active development, and may change at any time.',
1152 ' Make sure to monitor our mailing list for any updates.',
1154 'Erroneous requests: When erroneous requests are sent to the API, a HTTP header will be sent',
1155 ' with the key "MediaWiki-API-Error" and then both the value of the',
1156 ' header and the error code sent back will be set to the same value.',
1158 ' In the case of an invalid action being passed, these will have a value',
1159 ' of "unknown_action".',
1161 ' For more information see https://www.mediawiki.org' .
1162 '/wiki/API:Errors_and_warnings',
1164 'Documentation: https://www.mediawiki.org/wiki/API:Main_page',
1165 'FAQ https://www.mediawiki.org/wiki/API:FAQ',
1166 'Mailing list: https://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
1167 'Api Announcements: https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce',
1168 'Bugs & Requests: https://bugzilla.wikimedia.org/buglist.cgi?component=API&' .
1169 'bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
1181 public function getPossibleErrors() {
1182 return array_merge( parent
::getPossibleErrors(), array(
1183 array( 'readonlytext' ),
1184 array( 'code' => 'unknown_format', 'info' => 'Unrecognized format: format' ),
1185 array( 'code' => 'unknown_action', 'info' => 'The API requires a valid action parameter' ),
1186 array( 'code' => 'maxlag', 'info' => 'Waiting for host: x seconds lagged' ),
1187 array( 'code' => 'maxlag', 'info' => 'Waiting for a database server: x seconds lagged' ),
1188 array( 'code' => 'assertuserfailed', 'info' => 'Assertion that the user is logged in failed' ),
1190 'code' => 'assertbotfailed',
1191 'info' => 'Assertion that the user has the bot right failed'
1197 * Returns an array of strings with credits for the API
1200 protected function getCredits() {
1203 ' Roan Kattouw (lead developer Sep 2007-2009)',
1207 ' Yuri Astrakhan (creator, lead developer Sep 2006-Sep 2007, 2012-present)',
1209 'Please send your comments, suggestions and questions to mediawiki-api@lists.wikimedia.org',
1210 'or file a bug report at https://bugzilla.wikimedia.org/'
1215 * Sets whether the pretty-printer should format *bold* and $italics$
1219 public function setHelp( $help = true ) {
1220 $this->mPrinter
->setHelp( $help );
1224 * Override the parent to generate help messages for all available modules.
1228 public function makeHelpMsg() {
1229 global $wgMemc, $wgAPICacheHelpTimeout;
1231 // Get help text from cache if present
1232 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1233 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) ) );
1234 if ( $wgAPICacheHelpTimeout > 0 ) {
1235 $cached = $wgMemc->get( $key );
1240 $retval = $this->reallyMakeHelpMsg();
1241 if ( $wgAPICacheHelpTimeout > 0 ) {
1242 $wgMemc->set( $key, $retval, $wgAPICacheHelpTimeout );
1249 * @return mixed|string
1251 public function reallyMakeHelpMsg() {
1254 // Use parent to make default message for the main module
1255 $msg = parent
::makeHelpMsg();
1257 $astriks = str_repeat( '*** ', 14 );
1258 $msg .= "\n\n$astriks Modules $astriks\n\n";
1260 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1261 $module = $this->mModuleMgr
->getModule( $name );
1262 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1264 $msg2 = $module->makeHelpMsg();
1265 if ( $msg2 !== false ) {
1271 $msg .= "\n$astriks Permissions $astriks\n\n";
1272 foreach ( self
::$mRights as $right => $rightMsg ) {
1273 $groups = User
::getGroupsWithPermission( $right );
1274 $msg .= "* " . $right . " *\n " . wfMsgReplaceArgs( $rightMsg['msg'], $rightMsg['params'] ) .
1275 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1278 $msg .= "\n$astriks Formats $astriks\n\n";
1279 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1280 $module = $this->mModuleMgr
->getModule( $name );
1281 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1282 $msg2 = $module->makeHelpMsg();
1283 if ( $msg2 !== false ) {
1289 $msg .= "\n*** Credits: ***\n " . implode( "\n ", $this->getCredits() ) . "\n";
1295 * @param $module ApiBase
1296 * @param string $paramName What type of request is this? e.g. action,
1297 * query, list, prop, meta, format
1300 public static function makeHelpMsgHeader( $module, $paramName ) {
1301 $modulePrefix = $module->getModulePrefix();
1302 if ( strval( $modulePrefix ) !== '' ) {
1303 $modulePrefix = "($modulePrefix) ";
1306 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1309 private $mCanApiHighLimits = null;
1312 * Check whether the current user is allowed to use high limits
1315 public function canApiHighLimits() {
1316 if ( !isset( $this->mCanApiHighLimits
) ) {
1317 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1320 return $this->mCanApiHighLimits
;
1324 * Check whether the user wants us to show version information in the API help
1326 * @deprecated since 1.21, always returns false
1328 public function getShowVersions() {
1329 wfDeprecated( __METHOD__
, '1.21' );
1335 * Overrides to return this instance's module manager.
1336 * @return ApiModuleManager
1338 public function getModuleManager() {
1339 return $this->mModuleMgr
;
1343 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1344 * classes who wish to add their own modules to their lexicon or override the
1345 * behavior of inherent ones.
1347 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1348 * @param string $name The identifier for this module.
1349 * @param $class ApiBase The class where this module is implemented.
1351 protected function addModule( $name, $class ) {
1352 $this->getModuleManager()->addModule( $name, 'action', $class );
1356 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1357 * classes who wish to add to or modify current formatters.
1359 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1360 * @param string $name The identifier for this format.
1361 * @param $class ApiFormatBase The class implementing this format.
1363 protected function addFormat( $name, $class ) {
1364 $this->getModuleManager()->addModule( $name, 'format', $class );
1368 * Get the array mapping module names to class names
1369 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1372 function getModules() {
1373 return $this->getModuleManager()->getNamesWithClasses( 'action' );
1377 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1380 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1383 public function getFormats() {
1384 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1389 * This exception will be thrown when dieUsage is called to stop module execution.
1390 * The exception handling code will print a help screen explaining how this API may be used.
1394 class UsageException
extends MWException
{
1401 private $mExtraData;
1404 * @param $message string
1405 * @param $codestr string
1407 * @param $extradata array|null
1409 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1410 parent
::__construct( $message, $code );
1411 $this->mCodestr
= $codestr;
1412 $this->mExtraData
= $extradata;
1418 public function getCodeString() {
1419 return $this->mCodestr
;
1425 public function getMessageArray() {
1427 'code' => $this->mCodestr
,
1428 'info' => $this->getMessage()
1430 if ( is_array( $this->mExtraData
) ) {
1431 $result = array_merge( $result, $this->mExtraData
);
1440 public function __toString() {
1441 return "{$this->getCodeString()}: {$this->getMessage()}";