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 'delete' => 'ApiDelete',
72 'undelete' => 'ApiUndelete',
73 'protect' => 'ApiProtect',
74 'block' => 'ApiBlock',
75 'unblock' => 'ApiUnblock',
77 'edit' => 'ApiEditPage',
78 'upload' => 'ApiUpload',
79 'filerevert' => 'ApiFileRevert',
80 'emailuser' => 'ApiEmailUser',
81 'watch' => 'ApiWatch',
82 'patrol' => 'ApiPatrol',
83 'import' => 'ApiImport',
84 'userrights' => 'ApiUserrights',
85 'options' => 'ApiOptions',
86 'imagerotate' => 'ApiImageRotate',
87 'revisiondelete' => 'ApiRevisionDelete',
91 * List of available formats: format name => format class
93 private static $Formats = array(
94 'json' => 'ApiFormatJson',
95 'jsonfm' => 'ApiFormatJson',
96 'php' => 'ApiFormatPhp',
97 'phpfm' => 'ApiFormatPhp',
98 'wddx' => 'ApiFormatWddx',
99 'wddxfm' => 'ApiFormatWddx',
100 'xml' => 'ApiFormatXml',
101 'xmlfm' => 'ApiFormatXml',
102 'yaml' => 'ApiFormatYaml',
103 'yamlfm' => 'ApiFormatYaml',
104 'rawfm' => 'ApiFormatJson',
105 'txt' => 'ApiFormatTxt',
106 'txtfm' => 'ApiFormatTxt',
107 'dbg' => 'ApiFormatDbg',
108 'dbgfm' => 'ApiFormatDbg',
109 'dump' => 'ApiFormatDump',
110 'dumpfm' => 'ApiFormatDump',
111 'none' => 'ApiFormatNone',
114 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
116 * List of user roles that are specifically relevant to the API.
117 * array( 'right' => array ( 'msg' => 'Some message with a $1',
118 * 'params' => array ( $someVarToSubst ) ),
121 private static $mRights = array(
123 'msg' => 'Use of the write API',
126 'apihighlimits' => array(
127 '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.',
128 'params' => array( ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
)
131 // @codingStandardsIgnoreEnd
138 private $mModuleMgr, $mResult;
140 private $mEnableWrite;
141 private $mInternalMode, $mSquidMaxage, $mModule;
143 private $mCacheMode = 'private';
144 private $mCacheControl = array();
145 private $mParamsUsed = array();
148 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
150 * @param IContextSource|WebRequest $context If this is an instance of
151 * FauxRequest, errors are thrown and no printing occurs
152 * @param bool $enableWrite Should be set to true if the api may modify data
154 public function __construct( $context = null, $enableWrite = false ) {
155 if ( $context === null ) {
156 $context = RequestContext
::getMain();
157 } elseif ( $context instanceof WebRequest
) {
160 $context = RequestContext
::getMain();
162 // We set a derivative context so we can change stuff later
163 $this->setContext( new DerivativeContext( $context ) );
165 if ( isset( $request ) ) {
166 $this->getContext()->setRequest( $request );
169 $this->mInternalMode
= ( $this->getRequest() instanceof FauxRequest
);
171 // Special handling for the main module: $parent === $this
172 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
174 if ( !$this->mInternalMode
) {
175 // Impose module restrictions.
176 // If the current user cannot read,
177 // Remove all modules other than login
180 if ( $this->getVal( 'callback' ) !== null ) {
181 // JSON callback allows cross-site reads.
182 // For safety, strip user credentials.
183 wfDebug( "API: stripping user credentials for JSON callback\n" );
184 $wgUser = new User();
185 $this->getContext()->setUser( $wgUser );
189 global $wgAPIModules, $wgAPIFormatModules;
190 $this->mModuleMgr
= new ApiModuleManager( $this );
191 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
192 $this->mModuleMgr
->addModules( $wgAPIModules, 'action' );
193 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
194 $this->mModuleMgr
->addModules( $wgAPIFormatModules, 'format' );
196 $this->mResult
= new ApiResult( $this );
197 $this->mEnableWrite
= $enableWrite;
199 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
200 $this->mCommit
= false;
204 * Return true if the API was started by other PHP code using FauxRequest
207 public function isInternalMode() {
208 return $this->mInternalMode
;
212 * Get the ApiResult object associated with current request
216 public function getResult() {
217 return $this->mResult
;
221 * Get the API module object. Only works after executeAction()
225 public function getModule() {
226 return $this->mModule
;
230 * Get the result formatter object. Only works after setupExecuteAction()
232 * @return ApiFormatBase
234 public function getPrinter() {
235 return $this->mPrinter
;
239 * Set how long the response should be cached.
243 public function setCacheMaxAge( $maxage ) {
244 $this->setCacheControl( array(
245 'max-age' => $maxage,
246 's-maxage' => $maxage
251 * Set the type of caching headers which will be sent.
253 * @param string $mode One of:
254 * - 'public': Cache this object in public caches, if the maxage or smaxage
255 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
256 * not provided by any of these means, the object will be private.
257 * - 'private': Cache this object only in private client-side caches.
258 * - 'anon-public-user-private': Make this object cacheable for logged-out
259 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
260 * set consistently for a given URL, it cannot be set differently depending on
261 * things like the contents of the database, or whether the user is logged in.
263 * If the wiki does not allow anonymous users to read it, the mode set here
264 * will be ignored, and private caching headers will always be sent. In other words,
265 * the "public" mode is equivalent to saying that the data sent is as public as a page
268 * For user-dependent data, the private mode should generally be used. The
269 * anon-public-user-private mode should only be used where there is a particularly
270 * good performance reason for caching the anonymous response, but where the
271 * response to logged-in users may differ, or may contain private data.
273 * If this function is never called, then the default will be the private mode.
275 public function setCacheMode( $mode ) {
276 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
277 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
279 // Ignore for forwards-compatibility
283 if ( !User
::isEveryoneAllowed( 'read' ) ) {
284 // Private wiki, only private headers
285 if ( $mode !== 'private' ) {
286 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
292 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
293 $this->mCacheMode
= $mode;
297 * Set directives (key/value pairs) for the Cache-Control header.
298 * Boolean values will be formatted as such, by including or omitting
299 * without an equals sign.
301 * Cache control values set here will only be used if the cache mode is not
302 * private, see setCacheMode().
304 * @param array $directives
306 public function setCacheControl( $directives ) {
307 $this->mCacheControl
= $directives +
$this->mCacheControl
;
311 * Create an instance of an output formatter by its name
313 * @param string $format
315 * @return ApiFormatBase
317 public function createPrinterByName( $format ) {
318 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
319 if ( $printer === null ) {
320 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
327 * Execute api request. Any errors will be handled if the API was called by the remote client.
329 public function execute() {
331 if ( $this->mInternalMode
) {
332 $this->executeAction();
334 $this->executeActionWithErrorHandling();
341 * Execute an action, and in case of an error, erase whatever partial results
342 * have been accumulated, and replace it with an error message and a help screen.
344 protected function executeActionWithErrorHandling() {
345 // Verify the CORS header before executing the action
346 if ( !$this->handleCORS() ) {
347 // handleCORS() has sent a 403, abort
351 // Exit here if the request method was OPTIONS
352 // (assume there will be a followup GET or POST)
353 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
357 // In case an error occurs during data output,
358 // clear the output buffer and print just the error information
361 $t = microtime( true );
363 $this->executeAction();
364 } catch ( Exception
$e ) {
365 $this->handleException( $e );
368 // Log the request whether or not there was an error
369 $this->logRequest( microtime( true ) - $t );
371 // Send cache headers after any code which might generate an error, to
372 // avoid sending public cache headers for errors.
373 $this->sendCacheHeaders();
375 if ( $this->mPrinter
->getIsHtml() && !$this->mPrinter
->isDisabled() ) {
383 * Handle an exception as an API response
386 * @param Exception $e
388 protected function handleException( Exception
$e ) {
389 // Bug 63145: Rollback any open database transactions
390 if ( !( $e instanceof UsageException
) ) {
391 // UsageExceptions are intentional, so don't rollback if that's the case
392 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
395 // Allow extra cleanup and logging
396 wfRunHooks( 'ApiMain::onException', array( $this, $e ) );
399 if ( !( $e instanceof UsageException
) ) {
400 MWExceptionHandler
::logException( $e );
403 // Handle any kind of exception by outputting properly formatted error message.
404 // If this fails, an unhandled exception should be thrown so that global error
405 // handler will process and log it.
407 $errCode = $this->substituteResultWithError( $e );
409 // Error results should not be cached
410 $this->setCacheMode( 'private' );
412 $response = $this->getRequest()->response();
413 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
414 if ( $e->getCode() === 0 ) {
415 $response->header( $headerStr );
417 $response->header( $headerStr, true, $e->getCode() );
420 // Reset and print just the error message
423 // If the error occurred during printing, do a printer->profileOut()
424 $this->mPrinter
->safeProfileOut();
425 $this->printResult( true );
429 * Handle an exception from the ApiBeforeMain hook.
431 * This tries to print the exception as an API response, to be more
432 * friendly to clients. If it fails, it will rethrow the exception.
435 * @param Exception $e
437 public static function handleApiBeforeMainException( Exception
$e ) {
441 $main = new self( RequestContext
::getMain(), false );
442 $main->handleException( $e );
443 } catch ( Exception
$e2 ) {
444 // Nope, even that didn't work. Punt.
448 // Log the request and reset cache headers
449 $main->logRequest( 0 );
450 $main->sendCacheHeaders();
456 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
458 * If no origin parameter is present, nothing happens.
459 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
460 * is set and false is returned.
461 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
462 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
465 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
467 protected function handleCORS() {
468 global $wgCrossSiteAJAXdomains, $wgCrossSiteAJAXdomainExceptions;
470 $originParam = $this->getParameter( 'origin' ); // defaults to null
471 if ( $originParam === null ) {
472 // No origin parameter, nothing to do
476 $request = $this->getRequest();
477 $response = $request->response();
478 // Origin: header is a space-separated list of origins, check all of them
479 $originHeader = $request->getHeader( 'Origin' );
480 if ( $originHeader === false ) {
483 $origins = explode( ' ', $originHeader );
486 if ( !in_array( $originParam, $origins ) ) {
487 // origin parameter set but incorrect
488 // Send a 403 response
489 $message = HttpStatus
::getMessage( 403 );
490 $response->header( "HTTP/1.1 403 $message", true, 403 );
491 $response->header( 'Cache-Control: no-cache' );
492 echo "'origin' parameter does not match Origin header\n";
497 $matchOrigin = self
::matchOrigin(
499 $wgCrossSiteAJAXdomains,
500 $wgCrossSiteAJAXdomainExceptions
503 if ( $matchOrigin ) {
504 $response->header( "Access-Control-Allow-Origin: $originParam" );
505 $response->header( 'Access-Control-Allow-Credentials: true' );
506 $this->getOutput()->addVaryHeader( 'Origin' );
513 * Attempt to match an Origin header against a set of rules and a set of exceptions
514 * @param string $value Origin header
515 * @param array $rules Set of wildcard rules
516 * @param array $exceptions Set of wildcard rules
517 * @return bool True if $value matches a rule in $rules and doesn't match
518 * any rules in $exceptions, false otherwise
520 protected static function matchOrigin( $value, $rules, $exceptions ) {
521 foreach ( $rules as $rule ) {
522 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
523 // Rule matches, check exceptions
524 foreach ( $exceptions as $exc ) {
525 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
538 * Helper function to convert wildcard string into a regex
542 * @param string $wildcard String with wildcards
543 * @return string Regular expression
545 protected static function wildcardToRegex( $wildcard ) {
546 $wildcard = preg_quote( $wildcard, '/' );
547 $wildcard = str_replace(
553 return "/https?:\/\/$wildcard/";
556 protected function sendCacheHeaders() {
557 global $wgUseXVO, $wgVaryOnXFP;
558 $response = $this->getRequest()->response();
559 $out = $this->getOutput();
561 if ( $wgVaryOnXFP ) {
562 $out->addVaryHeader( 'X-Forwarded-Proto' );
565 if ( $this->mCacheMode
== 'private' ) {
566 $response->header( 'Cache-Control: private' );
571 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
572 $out->addVaryHeader( 'Cookie' );
573 $response->header( $out->getVaryHeader() );
575 $response->header( $out->getXVO() );
576 if ( $out->haveCacheVaryCookies() ) {
577 // Logged in, mark this request private
578 $response->header( 'Cache-Control: private' );
582 // Logged out, send normal public headers below
583 } elseif ( session_id() != '' ) {
584 // Logged in or otherwise has session (e.g. anonymous users who have edited)
585 // Mark request private
586 $response->header( 'Cache-Control: private' );
589 } // else no XVO and anonymous, send public headers below
592 // Send public headers
593 $response->header( $out->getVaryHeader() );
595 $response->header( $out->getXVO() );
598 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
599 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
600 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
602 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
603 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
606 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
607 // Public cache not requested
608 // Sending a Vary header in this case is harmless, and protects us
609 // against conditional calls of setCacheMaxAge().
610 $response->header( 'Cache-Control: private' );
615 $this->mCacheControl
['public'] = true;
617 // Send an Expires header
618 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
619 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
620 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
622 // Construct the Cache-Control header
625 foreach ( $this->mCacheControl
as $name => $value ) {
626 if ( is_bool( $value ) ) {
628 $ccHeader .= $separator . $name;
632 $ccHeader .= $separator . "$name=$value";
637 $response->header( "Cache-Control: $ccHeader" );
641 * Replace the result data with the information about an exception.
642 * Returns the error code
643 * @param Exception $e
646 protected function substituteResultWithError( $e ) {
647 global $wgShowHostnames;
649 $result = $this->getResult();
651 // Printer may not be initialized if the extractRequestParams() fails for the main module
652 if ( !isset( $this->mPrinter
) ) {
653 // The printer has not been created yet. Try to manually get formatter value.
654 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
655 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
656 $value = self
::API_DEFAULT_FORMAT
;
659 $this->mPrinter
= $this->createPrinterByName( $value );
662 // Printer may not be able to handle errors. This is particularly
663 // likely if the module returns something for getCustomPrinter().
664 if ( !$this->mPrinter
->canPrintErrors() ) {
665 $this->mPrinter
->safeProfileOut();
666 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
669 // Update raw mode flag for the selected printer.
670 $result->setRawMode( $this->mPrinter
->getNeedsRawData() );
672 if ( $e instanceof UsageException
) {
673 // User entered incorrect parameters - print usage screen
674 $errMessage = $e->getMessageArray();
676 // Only print the help message when this is for the developer, not runtime
677 if ( $this->mPrinter
->getWantsHelp() ||
$this->mAction
== 'help' ) {
678 ApiResult
::setContent( $errMessage, $this->makeHelpMsg() );
681 global $wgShowSQLErrors, $wgShowExceptionDetails;
682 // Something is seriously wrong
683 if ( ( $e instanceof DBQueryError
) && !$wgShowSQLErrors ) {
684 $info = 'Database query error';
686 $info = "Exception Caught: {$e->getMessage()}";
690 'code' => 'internal_api_error_' . get_class( $e ),
693 ApiResult
::setContent(
695 $wgShowExceptionDetails ?
"\n\n{$e->getTraceAsString()}\n\n" : ''
699 // Remember all the warnings to re-add them later
700 $oldResult = $result->getData();
701 $warnings = isset( $oldResult['warnings'] ) ?
$oldResult['warnings'] : null;
704 $result->disableSizeCheck();
706 $requestid = $this->getParameter( 'requestid' );
707 if ( !is_null( $requestid ) ) {
708 $result->addValue( null, 'requestid', $requestid );
710 if ( $wgShowHostnames ) {
711 // servedby is especially useful when debugging errors
712 $result->addValue( null, 'servedby', wfHostName() );
714 if ( $warnings !== null ) {
715 $result->addValue( null, 'warnings', $warnings );
718 $result->addValue( null, 'error', $errMessage );
720 return $errMessage['code'];
724 * Set up for the execution.
727 protected function setupExecuteAction() {
728 global $wgShowHostnames;
730 // First add the id to the top element
731 $result = $this->getResult();
732 $requestid = $this->getParameter( 'requestid' );
733 if ( !is_null( $requestid ) ) {
734 $result->addValue( null, 'requestid', $requestid );
737 if ( $wgShowHostnames ) {
738 $servedby = $this->getParameter( 'servedby' );
740 $result->addValue( null, 'servedby', wfHostName() );
744 $params = $this->extractRequestParams();
746 $this->mAction
= $params['action'];
748 if ( !is_string( $this->mAction
) ) {
749 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
756 * Set up the module for response
757 * @return ApiBase The module that will handle this action
759 protected function setupModule() {
760 // Instantiate the module requested by the user
761 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
762 if ( $module === null ) {
763 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
765 $moduleParams = $module->extractRequestParams();
767 // Die if token required, but not provided
768 $salt = $module->getTokenSalt();
769 if ( $salt !== false ) {
770 if ( !isset( $moduleParams['token'] ) ) {
771 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
774 if ( !$this->getUser()->matchEditToken(
775 $moduleParams['token'],
777 $this->getContext()->getRequest() )
779 $this->dieUsageMsg( 'sessionfailure' );
787 * Check the max lag if necessary
788 * @param ApiBase $module Api module being used
789 * @param array $params Array an array containing the request parameters.
790 * @return bool True on success, false should exit immediately
792 protected function checkMaxLag( $module, $params ) {
793 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
795 global $wgShowHostnames;
796 $maxLag = $params['maxlag'];
797 list( $host, $lag ) = wfGetLB()->getMaxLag();
798 if ( $lag > $maxLag ) {
799 $response = $this->getRequest()->response();
801 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
802 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
804 if ( $wgShowHostnames ) {
805 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
808 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
816 * Check for sufficient permissions to execute
817 * @param ApiBase $module An Api module
819 protected function checkExecutePermissions( $module ) {
820 $user = $this->getUser();
821 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
822 !$user->isAllowed( 'read' )
824 $this->dieUsageMsg( 'readrequired' );
826 if ( $module->isWriteMode() ) {
827 if ( !$this->mEnableWrite
) {
828 $this->dieUsageMsg( 'writedisabled' );
830 if ( !$user->isAllowed( 'writeapi' ) ) {
831 $this->dieUsageMsg( 'writerequired' );
833 if ( wfReadOnly() ) {
834 $this->dieReadOnly();
838 // Allow extensions to stop execution for arbitrary reasons.
840 if ( !wfRunHooks( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
841 $this->dieUsageMsg( $message );
846 * Check asserts of the user's rights
847 * @param array $params
849 protected function checkAsserts( $params ) {
850 if ( isset( $params['assert'] ) ) {
851 $user = $this->getUser();
852 switch ( $params['assert'] ) {
854 if ( $user->isAnon() ) {
855 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
859 if ( !$user->isAllowed( 'bot' ) ) {
860 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
868 * Check POST for external response and setup result printer
869 * @param ApiBase $module An Api module
870 * @param array $params an array with the request parameters
872 protected function setupExternalResponse( $module, $params ) {
873 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
874 // Module requires POST. GET request might still be allowed
875 // if $wgDebugApi is true, otherwise fail.
876 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction
) );
879 // See if custom printer is used
880 $this->mPrinter
= $module->getCustomPrinter();
881 if ( is_null( $this->mPrinter
) ) {
882 // Create an appropriate printer
883 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
886 if ( $this->mPrinter
->getNeedsRawData() ) {
887 $this->getResult()->setRawMode();
892 * Execute the actual module, without any error handling
894 protected function executeAction() {
895 $params = $this->setupExecuteAction();
896 $module = $this->setupModule();
897 $this->mModule
= $module;
899 $this->checkExecutePermissions( $module );
901 if ( !$this->checkMaxLag( $module, $params ) ) {
905 if ( !$this->mInternalMode
) {
906 $this->setupExternalResponse( $module, $params );
909 $this->checkAsserts( $params );
912 $module->profileIn();
914 wfRunHooks( 'APIAfterExecute', array( &$module ) );
915 $module->profileOut();
917 $this->reportUnusedParams();
919 if ( !$this->mInternalMode
) {
920 //append Debug information
921 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
924 $this->printResult( false );
929 * Log the preceding request
930 * @param int $time Time in seconds
932 protected function logRequest( $time ) {
933 $request = $this->getRequest();
934 $milliseconds = $time === null ?
'?' : round( $time * 1000 );
936 ' ' . $request->getMethod() .
937 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
938 ' ' . $request->getIP() .
939 ' T=' . $milliseconds . 'ms';
940 foreach ( $this->getParamsUsed() as $name ) {
941 $value = $request->getVal( $name );
942 if ( $value === null ) {
945 $s .= ' ' . $name . '=';
946 if ( strlen( $value ) > 256 ) {
947 $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
948 $s .= $encValue . '[...]';
950 $s .= $this->encodeRequestLogValue( $value );
954 wfDebugLog( 'api', $s, 'private' );
958 * Encode a value in a format suitable for a space-separated log line.
962 protected function encodeRequestLogValue( $s ) {
965 $chars = ';@$!*(),/:';
966 $numChars = strlen( $chars );
967 for ( $i = 0; $i < $numChars; $i++
) {
968 $table[rawurlencode( $chars[$i] )] = $chars[$i];
972 return strtr( rawurlencode( $s ), $table );
976 * Get the request parameters used in the course of the preceding execute() request
979 protected function getParamsUsed() {
980 return array_keys( $this->mParamsUsed
);
984 * Get a request value, and register the fact that it was used, for logging.
985 * @param string $name
986 * @param mixed $default
989 public function getVal( $name, $default = null ) {
990 $this->mParamsUsed
[$name] = true;
992 $ret = $this->getRequest()->getVal( $name );
993 if ( $ret === null ) {
994 if ( $this->getRequest()->getArray( $name ) !== null ) {
995 // See bug 10262 for why we don't just join( '|', ... ) the
998 "Parameter '$name' uses unsupported PHP array syntax"
1007 * Get a boolean request value, and register the fact that the parameter
1008 * was used, for logging.
1009 * @param string $name
1012 public function getCheck( $name ) {
1013 return $this->getVal( $name, null ) !== null;
1017 * Get a request upload, and register the fact that it was used, for logging.
1020 * @param string $name Parameter name
1021 * @return WebRequestUpload
1023 public function getUpload( $name ) {
1024 $this->mParamsUsed
[$name] = true;
1026 return $this->getRequest()->getUpload( $name );
1030 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1031 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1033 protected function reportUnusedParams() {
1034 $paramsUsed = $this->getParamsUsed();
1035 $allParams = $this->getRequest()->getValueNames();
1037 if ( !$this->mInternalMode
) {
1038 // Printer has not yet executed; don't warn that its parameters are unused
1039 $printerParams = array_map(
1040 array( $this->mPrinter
, 'encodeParamName' ),
1041 array_keys( $this->mPrinter
->getFinalParams() ?
: array() )
1043 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1045 $unusedParams = array_diff( $allParams, $paramsUsed );
1048 if ( count( $unusedParams ) ) {
1049 $s = count( $unusedParams ) > 1 ?
's' : '';
1050 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1055 * Print results using the current printer
1057 * @param bool $isError
1059 protected function printResult( $isError ) {
1061 if ( $wgDebugAPI !== false ) {
1062 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1065 $this->getResult()->cleanUpUTF8();
1066 $printer = $this->mPrinter
;
1067 $printer->profileIn();
1070 * If the help message is requested in the default (xmlfm) format,
1071 * tell the printer not to escape ampersands so that our links do
1074 $isHelp = $isError ||
$this->mAction
== 'help';
1075 $printer->setUnescapeAmps( $isHelp && $printer->getFormat() == 'XML' && $printer->getIsHtml() );
1077 $printer->initPrinter( $isHelp );
1079 $printer->execute();
1080 $printer->closePrinter();
1081 $printer->profileOut();
1087 public function isReadMode() {
1092 * See ApiBase for description.
1096 public function getAllowedParams() {
1099 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1100 ApiBase
::PARAM_TYPE
=> $this->mModuleMgr
->getNames( 'format' )
1103 ApiBase
::PARAM_DFLT
=> 'help',
1104 ApiBase
::PARAM_TYPE
=> $this->mModuleMgr
->getNames( 'action' )
1107 ApiBase
::PARAM_TYPE
=> 'integer'
1110 ApiBase
::PARAM_TYPE
=> 'integer',
1111 ApiBase
::PARAM_DFLT
=> 0
1114 ApiBase
::PARAM_TYPE
=> 'integer',
1115 ApiBase
::PARAM_DFLT
=> 0
1118 ApiBase
::PARAM_TYPE
=> array( 'user', 'bot' )
1120 'requestid' => null,
1121 'servedby' => false,
1127 * See ApiBase for description.
1131 public function getParamDescription() {
1133 'format' => 'The format of the output',
1134 'action' => 'What action you would like to perform. See below for module help',
1136 'Maximum lag can be used when MediaWiki is installed on a database replicated cluster.',
1137 'To save actions causing any more site replication lag, this parameter can make the client',
1138 'wait until the replication lag is less than the specified value.',
1139 'In case of a replag error, error code "maxlag" is returned, with the message like',
1140 '"Waiting for $host: $lag seconds lagged\n".',
1141 'See https://www.mediawiki.org/wiki/Manual:Maxlag_parameter for more information',
1143 'smaxage' => 'Set the s-maxage header to this many seconds. Errors are never cached',
1144 'maxage' => 'Set the max-age header to this many seconds. Errors are never cached',
1145 'assert' => 'Verify the user is logged in if set to "user", or has the bot userright if "bot"',
1146 'requestid' => 'Request ID to distinguish requests. This will just be output back to you',
1147 'servedby' => 'Include the hostname that served the request in the ' .
1148 'results. Unconditionally shown on error',
1150 'When accessing the API using a cross-domain AJAX request (CORS), set this to the',
1151 'originating domain. This must be included in any pre-flight request, and',
1152 'therefore must be part of the request URI (not the POST body). This must match',
1153 'one of the origins in the Origin: header exactly, so it has to be set to ',
1154 'something like http://en.wikipedia.org or https://meta.wikimedia.org . If this',
1155 'parameter does not match the Origin: header, a 403 response will be returned. If',
1156 'this parameter matches the Origin: header and the origin is whitelisted, an',
1157 'Access-Control-Allow-Origin header will be set.',
1163 * See ApiBase for description.
1167 public function getDescription() {
1171 '**********************************************************************************************',
1173 '** This is an auto-generated MediaWiki API documentation page **',
1175 '** Documentation and Examples: **',
1176 '** https://www.mediawiki.org/wiki/API **',
1178 '**********************************************************************************************',
1180 'Status: All features shown on this page should be working, but the API',
1181 ' is still in active development, and may change at any time.',
1182 ' Make sure to monitor our mailing list for any updates.',
1184 'Erroneous requests: When erroneous requests are sent to the API, a HTTP header will be sent',
1185 ' with the key "MediaWiki-API-Error" and then both the value of the',
1186 ' header and the error code sent back will be set to the same value.',
1188 ' In the case of an invalid action being passed, these will have a value',
1189 ' of "unknown_action".',
1191 ' For more information see https://www.mediawiki.org' .
1192 '/wiki/API:Errors_and_warnings',
1194 'Documentation: https://www.mediawiki.org/wiki/API:Main_page',
1195 'FAQ https://www.mediawiki.org/wiki/API:FAQ',
1196 'Mailing list: https://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
1197 'Api Announcements: https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce',
1198 'Bugs & Requests: https://bugzilla.wikimedia.org/buglist.cgi?component=API&' .
1199 'bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
1211 public function getPossibleErrors() {
1212 return array_merge( parent
::getPossibleErrors(), array(
1213 array( 'readonlytext' ),
1214 array( 'code' => 'unknown_format', 'info' => 'Unrecognized format: format' ),
1215 array( 'code' => 'unknown_action', 'info' => 'The API requires a valid action parameter' ),
1216 array( 'code' => 'maxlag', 'info' => 'Waiting for host: x seconds lagged' ),
1217 array( 'code' => 'maxlag', 'info' => 'Waiting for a database server: x seconds lagged' ),
1218 array( 'code' => 'assertuserfailed', 'info' => 'Assertion that the user is logged in failed' ),
1220 'code' => 'assertbotfailed',
1221 'info' => 'Assertion that the user has the bot right failed'
1227 * Returns an array of strings with credits for the API
1230 protected function getCredits() {
1233 ' Roan Kattouw (lead developer Sep 2007-2009)',
1237 ' Yuri Astrakhan (creator, lead developer Sep 2006-Sep 2007, 2012-present)',
1239 'Please send your comments, suggestions and questions to mediawiki-api@lists.wikimedia.org',
1240 'or file a bug report at https://bugzilla.wikimedia.org/'
1245 * Sets whether the pretty-printer should format *bold* and $italics$
1249 public function setHelp( $help = true ) {
1250 $this->mPrinter
->setHelp( $help );
1254 * Override the parent to generate help messages for all available modules.
1258 public function makeHelpMsg() {
1259 global $wgMemc, $wgAPICacheHelpTimeout;
1261 // Get help text from cache if present
1262 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1263 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) ) );
1264 if ( $wgAPICacheHelpTimeout > 0 ) {
1265 $cached = $wgMemc->get( $key );
1270 $retval = $this->reallyMakeHelpMsg();
1271 if ( $wgAPICacheHelpTimeout > 0 ) {
1272 $wgMemc->set( $key, $retval, $wgAPICacheHelpTimeout );
1279 * @return mixed|string
1281 public function reallyMakeHelpMsg() {
1284 // Use parent to make default message for the main module
1285 $msg = parent
::makeHelpMsg();
1287 $astriks = str_repeat( '*** ', 14 );
1288 $msg .= "\n\n$astriks Modules $astriks\n\n";
1290 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1291 $module = $this->mModuleMgr
->getModule( $name );
1292 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1294 $msg2 = $module->makeHelpMsg();
1295 if ( $msg2 !== false ) {
1301 $msg .= "\n$astriks Permissions $astriks\n\n";
1302 foreach ( self
::$mRights as $right => $rightMsg ) {
1303 $groups = User
::getGroupsWithPermission( $right );
1304 $msg .= "* " . $right . " *\n " . wfMsgReplaceArgs( $rightMsg['msg'], $rightMsg['params'] ) .
1305 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1308 $msg .= "\n$astriks Formats $astriks\n\n";
1309 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1310 $module = $this->mModuleMgr
->getModule( $name );
1311 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1312 $msg2 = $module->makeHelpMsg();
1313 if ( $msg2 !== false ) {
1319 $msg .= "\n*** Credits: ***\n " . implode( "\n ", $this->getCredits() ) . "\n";
1325 * @param ApiBase $module
1326 * @param string $paramName What type of request is this? e.g. action,
1327 * query, list, prop, meta, format
1330 public static function makeHelpMsgHeader( $module, $paramName ) {
1331 $modulePrefix = $module->getModulePrefix();
1332 if ( strval( $modulePrefix ) !== '' ) {
1333 $modulePrefix = "($modulePrefix) ";
1336 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1339 private $mCanApiHighLimits = null;
1342 * Check whether the current user is allowed to use high limits
1345 public function canApiHighLimits() {
1346 if ( !isset( $this->mCanApiHighLimits
) ) {
1347 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1350 return $this->mCanApiHighLimits
;
1354 * Check whether the user wants us to show version information in the API help
1356 * @deprecated since 1.21, always returns false
1358 public function getShowVersions() {
1359 wfDeprecated( __METHOD__
, '1.21' );
1365 * Overrides to return this instance's module manager.
1366 * @return ApiModuleManager
1368 public function getModuleManager() {
1369 return $this->mModuleMgr
;
1373 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1374 * classes who wish to add their own modules to their lexicon or override the
1375 * behavior of inherent ones.
1377 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1378 * @param string $name The identifier for this module.
1379 * @param ApiBase $class The class where this module is implemented.
1381 protected function addModule( $name, $class ) {
1382 $this->getModuleManager()->addModule( $name, 'action', $class );
1386 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1387 * classes who wish to add to or modify current formatters.
1389 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1390 * @param string $name The identifier for this format.
1391 * @param ApiFormatBase $class The class implementing this format.
1393 protected function addFormat( $name, $class ) {
1394 $this->getModuleManager()->addModule( $name, 'format', $class );
1398 * Get the array mapping module names to class names
1399 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1402 function getModules() {
1403 return $this->getModuleManager()->getNamesWithClasses( 'action' );
1407 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1410 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1413 public function getFormats() {
1414 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1419 * This exception will be thrown when dieUsage is called to stop module execution.
1420 * The exception handling code will print a help screen explaining how this API may be used.
1424 class UsageException
extends MWException
{
1431 private $mExtraData;
1434 * @param string $message
1435 * @param string $codestr
1437 * @param array|null $extradata
1439 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1440 parent
::__construct( $message, $code );
1441 $this->mCodestr
= $codestr;
1442 $this->mExtraData
= $extradata;
1448 public function getCodeString() {
1449 return $this->mCodestr
;
1455 public function getMessageArray() {
1457 'code' => $this->mCodestr
,
1458 'info' => $this->getMessage()
1460 if ( is_array( $this->mExtraData
) ) {
1461 $result = array_merge( $result, $this->mExtraData
);
1470 public function __toString() {
1471 return "{$this->getCodeString()}: {$this->getMessage()}";