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
{
44 * When no format parameter is given, this format will be used
46 const API_DEFAULT_FORMAT
= 'xmlfm';
49 * List of available modules: action name => module class
51 private static $Modules = array(
52 'login' => 'ApiLogin',
53 'logout' => 'ApiLogout',
54 'createaccount' => 'ApiCreateAccount',
55 'query' => 'ApiQuery',
56 'expandtemplates' => 'ApiExpandTemplates',
57 'parse' => 'ApiParse',
58 'opensearch' => 'ApiOpenSearch',
59 'feedcontributions' => 'ApiFeedContributions',
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',
90 * List of available formats: format name => format class
92 private static $Formats = array(
93 'json' => 'ApiFormatJson',
94 'jsonfm' => 'ApiFormatJson',
95 'php' => 'ApiFormatPhp',
96 'phpfm' => 'ApiFormatPhp',
97 'wddx' => 'ApiFormatWddx',
98 'wddxfm' => 'ApiFormatWddx',
99 'xml' => 'ApiFormatXml',
100 'xmlfm' => 'ApiFormatXml',
101 'yaml' => 'ApiFormatYaml',
102 'yamlfm' => 'ApiFormatYaml',
103 'rawfm' => 'ApiFormatJson',
104 'txt' => 'ApiFormatTxt',
105 'txtfm' => 'ApiFormatTxt',
106 'dbg' => 'ApiFormatDbg',
107 'dbgfm' => 'ApiFormatDbg',
108 'dump' => 'ApiFormatDump',
109 'dumpfm' => 'ApiFormatDump',
110 'none' => 'ApiFormatNone',
114 * List of user roles that are specifically relevant to the API.
115 * array( 'right' => array ( 'msg' => 'Some message with a $1',
116 * 'params' => array ( $someVarToSubst ) ),
119 private static $mRights = array(
121 'msg' => 'Use of the write API',
124 'apihighlimits' => array(
125 '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.',
126 'params' => array( ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
)
135 private $mModuleMgr, $mResult;
137 private $mEnableWrite;
138 private $mInternalMode, $mSquidMaxage, $mModule;
140 private $mCacheMode = 'private';
141 private $mCacheControl = array();
142 private $mParamsUsed = array();
145 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
147 * @param $context IContextSource|WebRequest - if this is an instance of FauxRequest, errors are thrown and no printing occurs
148 * @param bool $enableWrite should be set to true if the api may modify data
150 public function __construct( $context = null, $enableWrite = false ) {
151 if ( $context === null ) {
152 $context = RequestContext
::getMain();
153 } elseif ( $context instanceof WebRequest
) {
156 $context = RequestContext
::getMain();
158 // We set a derivative context so we can change stuff later
159 $this->setContext( new DerivativeContext( $context ) );
161 if ( isset( $request ) ) {
162 $this->getContext()->setRequest( $request );
165 $this->mInternalMode
= ( $this->getRequest() instanceof FauxRequest
);
167 // Special handling for the main module: $parent === $this
168 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
170 if ( !$this->mInternalMode
) {
171 // Impose module restrictions.
172 // If the current user cannot read,
173 // Remove all modules other than login
176 if ( $this->getVal( 'callback' ) !== null ) {
177 // JSON callback allows cross-site reads.
178 // For safety, strip user credentials.
179 wfDebug( "API: stripping user credentials for JSON callback\n" );
180 $wgUser = new User();
181 $this->getContext()->setUser( $wgUser );
185 global $wgAPIModules;
186 $this->mModuleMgr
= new ApiModuleManager( $this );
187 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
188 $this->mModuleMgr
->addModules( $wgAPIModules, 'action' );
189 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
191 $this->mResult
= new ApiResult( $this );
192 $this->mEnableWrite
= $enableWrite;
194 $this->mSquidMaxage
= - 1; // flag for executeActionWithErrorHandling()
195 $this->mCommit
= false;
199 * Return true if the API was started by other PHP code using FauxRequest
202 public function isInternalMode() {
203 return $this->mInternalMode
;
207 * Get the ApiResult object associated with current request
211 public function getResult() {
212 return $this->mResult
;
216 * Get the API module object. Only works after executeAction()
220 public function getModule() {
221 return $this->mModule
;
225 * Get the result formatter object. Only works after setupExecuteAction()
227 * @return ApiFormatBase
229 public function getPrinter() {
230 return $this->mPrinter
;
234 * Set how long the response should be cached.
238 public function setCacheMaxAge( $maxage ) {
239 $this->setCacheControl( array(
240 'max-age' => $maxage,
241 's-maxage' => $maxage
246 * Set the type of caching headers which will be sent.
248 * @param string $mode One of:
249 * - 'public': Cache this object in public caches, if the maxage or smaxage
250 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
251 * not provided by any of these means, the object will be private.
252 * - 'private': Cache this object only in private client-side caches.
253 * - 'anon-public-user-private': Make this object cacheable for logged-out
254 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
255 * set consistently for a given URL, it cannot be set differently depending on
256 * things like the contents of the database, or whether the user is logged in.
258 * If the wiki does not allow anonymous users to read it, the mode set here
259 * will be ignored, and private caching headers will always be sent. In other words,
260 * the "public" mode is equivalent to saying that the data sent is as public as a page
263 * For user-dependent data, the private mode should generally be used. The
264 * anon-public-user-private mode should only be used where there is a particularly
265 * good performance reason for caching the anonymous response, but where the
266 * response to logged-in users may differ, or may contain private data.
268 * If this function is never called, then the default will be the private mode.
270 public function setCacheMode( $mode ) {
271 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
272 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
273 // Ignore for forwards-compatibility
277 if ( !User
::isEveryoneAllowed( 'read' ) ) {
278 // Private wiki, only private headers
279 if ( $mode !== 'private' ) {
280 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
285 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
286 $this->mCacheMode
= $mode;
290 * @deprecated since 1.17 Private caching is now the default, so there is usually no
291 * need to call this function. If there is a need, you can use
292 * $this->setCacheMode('private')
294 public function setCachePrivate() {
295 wfDeprecated( __METHOD__
, '1.17' );
296 $this->setCacheMode( 'private' );
300 * Set directives (key/value pairs) for the Cache-Control header.
301 * Boolean values will be formatted as such, by including or omitting
302 * without an equals sign.
304 * Cache control values set here will only be used if the cache mode is not
305 * private, see setCacheMode().
307 * @param $directives array
309 public function setCacheControl( $directives ) {
310 $this->mCacheControl
= $directives +
$this->mCacheControl
;
314 * Make sure Vary: Cookie and friends are set. Use this when the output of a request
315 * may be cached for anons but may not be cached for logged-in users.
317 * WARNING: This function must be called CONSISTENTLY for a given URL. This means that a
318 * given URL must either always or never call this function; if it sometimes does and
319 * sometimes doesn't, stuff will break.
321 * @deprecated since 1.17 Use setCacheMode( 'anon-public-user-private' )
323 public function setVaryCookie() {
324 wfDeprecated( __METHOD__
, '1.17' );
325 $this->setCacheMode( 'anon-public-user-private' );
329 * Create an instance of an output formatter by its name
331 * @param $format string
333 * @return ApiFormatBase
335 public function createPrinterByName( $format ) {
336 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
337 if ( $printer === null ) {
338 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
344 * Execute api request. Any errors will be handled if the API was called by the remote client.
346 public function execute() {
348 if ( $this->mInternalMode
) {
349 $this->executeAction();
351 $this->executeActionWithErrorHandling();
358 * Execute an action, and in case of an error, erase whatever partial results
359 * have been accumulated, and replace it with an error message and a help screen.
361 protected function executeActionWithErrorHandling() {
362 // Verify the CORS header before executing the action
363 if ( !$this->handleCORS() ) {
364 // handleCORS() has sent a 403, abort
368 // Exit here if the request method was OPTIONS
369 // (assume there will be a followup GET or POST)
370 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
374 // In case an error occurs during data output,
375 // clear the output buffer and print just the error information
378 $t = microtime( true );
380 $this->executeAction();
381 } catch ( Exception
$e ) {
382 // Allow extra cleanup and logging
383 wfRunHooks( 'ApiMain::onException', array( $this, $e ) );
386 if ( !( $e instanceof UsageException
) ) {
387 MWExceptionHandler
::logException( $e );
390 // Handle any kind of exception by outputting properly formatted error message.
391 // If this fails, an unhandled exception should be thrown so that global error
392 // handler will process and log it.
394 $errCode = $this->substituteResultWithError( $e );
396 // Error results should not be cached
397 $this->setCacheMode( 'private' );
399 $response = $this->getRequest()->response();
400 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
401 if ( $e->getCode() === 0 ) {
402 $response->header( $headerStr );
404 $response->header( $headerStr, true, $e->getCode() );
407 // Reset and print just the error message
410 // If the error occurred during printing, do a printer->profileOut()
411 $this->mPrinter
->safeProfileOut();
412 $this->printResult( true );
415 // Log the request whether or not there was an error
416 $this->logRequest( microtime( true ) - $t );
418 // Send cache headers after any code which might generate an error, to
419 // avoid sending public cache headers for errors.
420 $this->sendCacheHeaders();
422 if ( $this->mPrinter
->getIsHtml() && !$this->mPrinter
->isDisabled() ) {
430 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
432 * If no origin parameter is present, nothing happens.
433 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
434 * is set and false is returned.
435 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
436 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
439 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
441 protected function handleCORS() {
442 global $wgCrossSiteAJAXdomains, $wgCrossSiteAJAXdomainExceptions;
444 $originParam = $this->getParameter( 'origin' ); // defaults to null
445 if ( $originParam === null ) {
446 // No origin parameter, nothing to do
450 $request = $this->getRequest();
451 $response = $request->response();
452 // Origin: header is a space-separated list of origins, check all of them
453 $originHeader = $request->getHeader( 'Origin' );
454 if ( $originHeader === false ) {
457 $origins = explode( ' ', $originHeader );
459 if ( !in_array( $originParam, $origins ) ) {
460 // origin parameter set but incorrect
461 // Send a 403 response
462 $message = HttpStatus
::getMessage( 403 );
463 $response->header( "HTTP/1.1 403 $message", true, 403 );
464 $response->header( 'Cache-Control: no-cache' );
465 echo "'origin' parameter does not match Origin header\n";
468 if ( self
::matchOrigin( $originParam, $wgCrossSiteAJAXdomains, $wgCrossSiteAJAXdomainExceptions ) ) {
469 $response->header( "Access-Control-Allow-Origin: $originParam" );
470 $response->header( 'Access-Control-Allow-Credentials: true' );
471 $this->getOutput()->addVaryHeader( 'Origin' );
477 * Attempt to match an Origin header against a set of rules and a set of exceptions
478 * @param string $value Origin header
479 * @param array $rules Set of wildcard rules
480 * @param array $exceptions Set of wildcard rules
481 * @return bool True if $value matches a rule in $rules and doesn't match any rules in $exceptions, false otherwise
483 protected static function matchOrigin( $value, $rules, $exceptions ) {
484 foreach ( $rules as $rule ) {
485 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
486 // Rule matches, check exceptions
487 foreach ( $exceptions as $exc ) {
488 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
499 * Helper function to convert wildcard string into a regex
503 * @param string $wildcard String with wildcards
504 * @return string Regular expression
506 protected static function wildcardToRegex( $wildcard ) {
507 $wildcard = preg_quote( $wildcard, '/' );
508 $wildcard = str_replace(
513 return "/https?:\/\/$wildcard/";
516 protected function sendCacheHeaders() {
517 global $wgUseXVO, $wgVaryOnXFP;
518 $response = $this->getRequest()->response();
519 $out = $this->getOutput();
521 if ( $wgVaryOnXFP ) {
522 $out->addVaryHeader( 'X-Forwarded-Proto' );
525 if ( $this->mCacheMode
== 'private' ) {
526 $response->header( 'Cache-Control: private' );
530 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
531 $out->addVaryHeader( 'Cookie' );
532 $response->header( $out->getVaryHeader() );
534 $response->header( $out->getXVO() );
535 if ( $out->haveCacheVaryCookies() ) {
536 // Logged in, mark this request private
537 $response->header( 'Cache-Control: private' );
540 // Logged out, send normal public headers below
541 } elseif ( session_id() != '' ) {
542 // Logged in or otherwise has session (e.g. anonymous users who have edited)
543 // Mark request private
544 $response->header( 'Cache-Control: private' );
546 } // else no XVO and anonymous, send public headers below
549 // Send public headers
550 $response->header( $out->getVaryHeader() );
552 $response->header( $out->getXVO() );
555 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
556 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
557 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
559 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
560 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
563 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
564 // Public cache not requested
565 // Sending a Vary header in this case is harmless, and protects us
566 // against conditional calls of setCacheMaxAge().
567 $response->header( 'Cache-Control: private' );
571 $this->mCacheControl
['public'] = true;
573 // Send an Expires header
574 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
575 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
576 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
578 // Construct the Cache-Control header
581 foreach ( $this->mCacheControl
as $name => $value ) {
582 if ( is_bool( $value ) ) {
584 $ccHeader .= $separator . $name;
588 $ccHeader .= $separator . "$name=$value";
593 $response->header( "Cache-Control: $ccHeader" );
597 * Replace the result data with the information about an exception.
598 * Returns the error code
599 * @param $e Exception
602 protected function substituteResultWithError( $e ) {
603 global $wgShowHostnames;
605 $result = $this->getResult();
606 // Printer may not be initialized if the extractRequestParams() fails for the main module
607 if ( !isset( $this->mPrinter
) ) {
608 // The printer has not been created yet. Try to manually get formatter value.
609 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
610 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
611 $value = self
::API_DEFAULT_FORMAT
;
614 $this->mPrinter
= $this->createPrinterByName( $value );
615 if ( $this->mPrinter
->getNeedsRawData() ) {
616 $result->setRawMode();
620 if ( $e instanceof UsageException
) {
621 // User entered incorrect parameters - print usage screen
622 $errMessage = $e->getMessageArray();
624 // Only print the help message when this is for the developer, not runtime
625 if ( $this->mPrinter
->getWantsHelp() ||
$this->mAction
== 'help' ) {
626 ApiResult
::setContent( $errMessage, $this->makeHelpMsg() );
629 global $wgShowSQLErrors, $wgShowExceptionDetails;
630 // Something is seriously wrong
631 if ( ( $e instanceof DBQueryError
) && !$wgShowSQLErrors ) {
632 $info = 'Database query error';
634 $info = "Exception Caught: {$e->getMessage()}";
638 'code' => 'internal_api_error_' . get_class( $e ),
641 ApiResult
::setContent( $errMessage, $wgShowExceptionDetails ?
"\n\n{$e->getTraceAsString()}\n\n" : '' );
644 // Remember all the warnings to re-add them later
645 $oldResult = $result->getData();
646 $warnings = isset( $oldResult['warnings'] ) ?
$oldResult['warnings'] : null;
649 $result->disableSizeCheck();
651 $requestid = $this->getParameter( 'requestid' );
652 if ( !is_null( $requestid ) ) {
653 $result->addValue( null, 'requestid', $requestid );
655 if ( $wgShowHostnames ) {
656 // servedby is especially useful when debugging errors
657 $result->addValue( null, 'servedby', wfHostName() );
659 if ( $warnings !== null ) {
660 $result->addValue( null, 'warnings', $warnings );
663 $result->addValue( null, 'error', $errMessage );
665 return $errMessage['code'];
669 * Set up for the execution.
672 protected function setupExecuteAction() {
673 global $wgShowHostnames;
675 // First add the id to the top element
676 $result = $this->getResult();
677 $requestid = $this->getParameter( 'requestid' );
678 if ( !is_null( $requestid ) ) {
679 $result->addValue( null, 'requestid', $requestid );
682 if ( $wgShowHostnames ) {
683 $servedby = $this->getParameter( 'servedby' );
685 $result->addValue( null, 'servedby', wfHostName() );
689 $params = $this->extractRequestParams();
691 $this->mAction
= $params['action'];
693 if ( !is_string( $this->mAction
) ) {
694 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
701 * Set up the module for response
702 * @return ApiBase The module that will handle this action
704 protected function setupModule() {
705 // Instantiate the module requested by the user
706 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
707 if ( $module === null ) {
708 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
710 $moduleParams = $module->extractRequestParams();
712 // Die if token required, but not provided
713 $salt = $module->getTokenSalt();
714 if ( $salt !== false ) {
715 if ( !isset( $moduleParams['token'] ) ) {
716 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
718 if ( !$this->getUser()->matchEditToken( $moduleParams['token'], $salt, $this->getContext()->getRequest() ) ) {
719 $this->dieUsageMsg( 'sessionfailure' );
727 * Check the max lag if necessary
728 * @param $module ApiBase object: Api module being used
729 * @param array $params an array containing the request parameters.
730 * @return boolean True on success, false should exit immediately
732 protected function checkMaxLag( $module, $params ) {
733 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
735 global $wgShowHostnames;
736 $maxLag = $params['maxlag'];
737 list( $host, $lag ) = wfGetLB()->getMaxLag();
738 if ( $lag > $maxLag ) {
739 $response = $this->getRequest()->response();
741 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
742 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
744 if ( $wgShowHostnames ) {
745 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
747 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
756 * Check for sufficient permissions to execute
757 * @param $module ApiBase An Api module
759 protected function checkExecutePermissions( $module ) {
760 $user = $this->getUser();
761 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
762 !$user->isAllowed( 'read' ) )
764 $this->dieUsageMsg( 'readrequired' );
766 if ( $module->isWriteMode() ) {
767 if ( !$this->mEnableWrite
) {
768 $this->dieUsageMsg( 'writedisabled' );
770 if ( !$user->isAllowed( 'writeapi' ) ) {
771 $this->dieUsageMsg( 'writerequired' );
773 if ( wfReadOnly() ) {
774 $this->dieReadOnly();
778 // Allow extensions to stop execution for arbitrary reasons.
780 if ( !wfRunHooks( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
781 $this->dieUsageMsg( $message );
786 * Check POST for external response and setup result printer
787 * @param $module ApiBase An Api module
788 * @param array $params an array with the request parameters
790 protected function setupExternalResponse( $module, $params ) {
791 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
792 // Module requires POST. GET request might still be allowed
793 // if $wgDebugApi is true, otherwise fail.
794 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction
) );
797 // See if custom printer is used
798 $this->mPrinter
= $module->getCustomPrinter();
799 if ( is_null( $this->mPrinter
) ) {
800 // Create an appropriate printer
801 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
804 if ( $this->mPrinter
->getNeedsRawData() ) {
805 $this->getResult()->setRawMode();
810 * Execute the actual module, without any error handling
812 protected function executeAction() {
813 $params = $this->setupExecuteAction();
814 $module = $this->setupModule();
815 $this->mModule
= $module;
817 $this->checkExecutePermissions( $module );
819 if ( !$this->checkMaxLag( $module, $params ) ) {
823 if ( !$this->mInternalMode
) {
824 $this->setupExternalResponse( $module, $params );
828 $module->profileIn();
830 wfRunHooks( 'APIAfterExecute', array( &$module ) );
831 $module->profileOut();
833 $this->reportUnusedParams();
835 if ( !$this->mInternalMode
) {
836 //append Debug information
837 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
840 $this->printResult( false );
845 * Log the preceding request
846 * @param $time Time in seconds
848 protected function logRequest( $time ) {
849 $request = $this->getRequest();
850 $milliseconds = $time === null ?
'?' : round( $time * 1000 );
852 ' ' . $request->getMethod() .
853 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
854 ' ' . $request->getIP() .
855 ' T=' . $milliseconds . 'ms';
856 foreach ( $this->getParamsUsed() as $name ) {
857 $value = $request->getVal( $name );
858 if ( $value === null ) {
861 $s .= ' ' . $name . '=';
862 if ( strlen( $value ) > 256 ) {
863 $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
864 $s .= $encValue . '[...]';
866 $s .= $this->encodeRequestLogValue( $value );
870 wfDebugLog( 'api', $s, false );
874 * Encode a value in a format suitable for a space-separated log line.
876 protected function encodeRequestLogValue( $s ) {
879 $chars = ';@$!*(),/:';
880 for ( $i = 0; $i < strlen( $chars ); $i++
) {
881 $table[rawurlencode( $chars[$i] )] = $chars[$i];
884 return strtr( rawurlencode( $s ), $table );
888 * Get the request parameters used in the course of the preceding execute() request
890 protected function getParamsUsed() {
891 return array_keys( $this->mParamsUsed
);
895 * Get a request value, and register the fact that it was used, for logging.
897 public function getVal( $name, $default = null ) {
898 $this->mParamsUsed
[$name] = true;
899 return $this->getRequest()->getVal( $name, $default );
903 * Get a boolean request value, and register the fact that the parameter
904 * was used, for logging.
906 public function getCheck( $name ) {
907 $this->mParamsUsed
[$name] = true;
908 return $this->getRequest()->getCheck( $name );
912 * Get a request upload, and register the fact that it was used, for logging.
915 * @param string $name Parameter name
916 * @return WebRequestUpload
918 public function getUpload( $name ) {
919 $this->mParamsUsed
[$name] = true;
920 return $this->getRequest()->getUpload( $name );
924 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
925 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
927 protected function reportUnusedParams() {
928 $paramsUsed = $this->getParamsUsed();
929 $allParams = $this->getRequest()->getValueNames();
931 if ( !$this->mInternalMode
) {
932 // Printer has not yet executed; don't warn that its parameters are unused
933 $printerParams = array_map(
934 array( $this->mPrinter
, 'encodeParamName' ),
935 array_keys( $this->mPrinter
->getFinalParams() ?
: array() )
937 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
939 $unusedParams = array_diff( $allParams, $paramsUsed );
942 if ( count( $unusedParams ) ) {
943 $s = count( $unusedParams ) > 1 ?
's' : '';
944 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
949 * Print results using the current printer
951 * @param $isError bool
953 protected function printResult( $isError ) {
955 if ( $wgDebugAPI !== false ) {
956 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
959 $this->getResult()->cleanUpUTF8();
960 $printer = $this->mPrinter
;
961 $printer->profileIn();
964 * If the help message is requested in the default (xmlfm) format,
965 * tell the printer not to escape ampersands so that our links do
968 $isHelp = $isError ||
$this->mAction
== 'help';
969 $printer->setUnescapeAmps( $isHelp && $printer->getFormat() == 'XML' && $printer->getIsHtml() );
971 $printer->initPrinter( $isHelp );
974 $printer->closePrinter();
975 $printer->profileOut();
981 public function isReadMode() {
986 * See ApiBase for description.
990 public function getAllowedParams() {
993 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
994 ApiBase
::PARAM_TYPE
=> $this->mModuleMgr
->getNames( 'format' )
997 ApiBase
::PARAM_DFLT
=> 'help',
998 ApiBase
::PARAM_TYPE
=> $this->mModuleMgr
->getNames( 'action' )
1001 ApiBase
::PARAM_TYPE
=> 'integer'
1004 ApiBase
::PARAM_TYPE
=> 'integer',
1005 ApiBase
::PARAM_DFLT
=> 0
1008 ApiBase
::PARAM_TYPE
=> 'integer',
1009 ApiBase
::PARAM_DFLT
=> 0
1011 'requestid' => null,
1012 'servedby' => false,
1018 * See ApiBase for description.
1022 public function getParamDescription() {
1024 'format' => 'The format of the output',
1025 'action' => 'What action you would like to perform. See below for module help',
1027 'Maximum lag can be used when MediaWiki is installed on a database replicated cluster.',
1028 'To save actions causing any more site replication lag, this parameter can make the client',
1029 'wait until the replication lag is less than the specified value.',
1030 'In case of a replag error, error code "maxlag" is returned, with the message like',
1031 '"Waiting for $host: $lag seconds lagged\n".',
1032 'See https://www.mediawiki.org/wiki/Manual:Maxlag_parameter for more information',
1034 'smaxage' => 'Set the s-maxage header to this many seconds. Errors are never cached',
1035 'maxage' => 'Set the max-age header to this many seconds. Errors are never cached',
1036 'requestid' => 'Request ID to distinguish requests. This will just be output back to you',
1037 'servedby' => 'Include the hostname that served the request in the results. Unconditionally shown on error',
1039 'When accessing the API using a cross-domain AJAX request (CORS), set this to the originating domain.',
1040 'This must be included in any pre-flight request, and therefore must be part of the request URI (not the POST body).',
1041 'This must match one of the origins in the Origin: header exactly, so it has to be set to something like http://en.wikipedia.org or https://meta.wikimedia.org .',
1042 'If this parameter does not match the Origin: header, a 403 response will be returned.',
1043 'If this parameter matches the Origin: header and the origin is whitelisted, an Access-Control-Allow-Origin header will be set.',
1049 * See ApiBase for description.
1053 public function getDescription() {
1057 '**********************************************************************************************************',
1059 '** This is an auto-generated MediaWiki API documentation page **',
1061 '** Documentation and Examples: **',
1062 '** https://www.mediawiki.org/wiki/API **',
1064 '**********************************************************************************************************',
1066 'Status: All features shown on this page should be working, but the API',
1067 ' is still in active development, and may change at any time.',
1068 ' Make sure to monitor our mailing list for any updates',
1070 'Erroneous requests: When erroneous requests are sent to the API, a HTTP header will be sent',
1071 ' with the key "MediaWiki-API-Error" and then both the value of the',
1072 ' header and the error code sent back will be set to the same value',
1074 ' In the case of an invalid action being passed, these will have a value',
1075 ' of "unknown_action"',
1077 ' For more information see https://www.mediawiki.org/wiki/API:Errors_and_warnings',
1079 'Documentation: https://www.mediawiki.org/wiki/API:Main_page',
1080 'FAQ https://www.mediawiki.org/wiki/API:FAQ',
1081 'Mailing list: https://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
1082 'Api Announcements: https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce',
1083 'Bugs & Requests: https://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
1095 public function getPossibleErrors() {
1096 return array_merge( parent
::getPossibleErrors(), array(
1097 array( 'readonlytext' ),
1098 array( 'code' => 'unknown_format', 'info' => 'Unrecognized format: format' ),
1099 array( 'code' => 'unknown_action', 'info' => 'The API requires a valid action parameter' ),
1100 array( 'code' => 'maxlag', 'info' => 'Waiting for host: x seconds lagged' ),
1101 array( 'code' => 'maxlag', 'info' => 'Waiting for a database server: x seconds lagged' ),
1106 * Returns an array of strings with credits for the API
1109 protected function getCredits() {
1112 ' Roan Kattouw "<Firstname>.<Lastname>@gmail.com" (lead developer Sep 2007-2009)',
1113 ' Victor Vasiliev - vasilvv @ gmail . com',
1114 ' Bryan Tong Minh - bryan . tongminh @ gmail . com',
1115 ' Sam Reed - sam @ reedyboy . net',
1116 ' Yuri Astrakhan "<Firstname><Lastname>@gmail.com" (creator, lead developer Sep 2006-Sep 2007, 2012-present)',
1118 'Please send your comments, suggestions and questions to mediawiki-api@lists.wikimedia.org',
1119 'or file a bug report at https://bugzilla.wikimedia.org/'
1124 * Sets whether the pretty-printer should format *bold* and $italics$
1128 public function setHelp( $help = true ) {
1129 $this->mPrinter
->setHelp( $help );
1133 * Override the parent to generate help messages for all available modules.
1137 public function makeHelpMsg() {
1138 global $wgMemc, $wgAPICacheHelpTimeout;
1140 // Get help text from cache if present
1141 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1142 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) ) );
1143 if ( $wgAPICacheHelpTimeout > 0 ) {
1144 $cached = $wgMemc->get( $key );
1149 $retval = $this->reallyMakeHelpMsg();
1150 if ( $wgAPICacheHelpTimeout > 0 ) {
1151 $wgMemc->set( $key, $retval, $wgAPICacheHelpTimeout );
1157 * @return mixed|string
1159 public function reallyMakeHelpMsg() {
1162 // Use parent to make default message for the main module
1163 $msg = parent
::makeHelpMsg();
1165 $astriks = str_repeat( '*** ', 14 );
1166 $msg .= "\n\n$astriks Modules $astriks\n\n";
1168 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1169 $module = $this->mModuleMgr
->getModule( $name );
1170 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1172 $msg2 = $module->makeHelpMsg();
1173 if ( $msg2 !== false ) {
1179 $msg .= "\n$astriks Permissions $astriks\n\n";
1180 foreach ( self
::$mRights as $right => $rightMsg ) {
1181 $groups = User
::getGroupsWithPermission( $right );
1182 $msg .= "* " . $right . " *\n " . wfMsgReplaceArgs( $rightMsg['msg'], $rightMsg['params'] ) .
1183 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1186 $msg .= "\n$astriks Formats $astriks\n\n";
1187 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1188 $module = $this->mModuleMgr
->getModule( $name );
1189 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1190 $msg2 = $module->makeHelpMsg();
1191 if ( $msg2 !== false ) {
1197 $msg .= "\n*** Credits: ***\n " . implode( "\n ", $this->getCredits() ) . "\n";
1203 * @param $module ApiBase
1204 * @param string $paramName What type of request is this? e.g. action, query, list, prop, meta, format
1207 public static function makeHelpMsgHeader( $module, $paramName ) {
1208 $modulePrefix = $module->getModulePrefix();
1209 if ( strval( $modulePrefix ) !== '' ) {
1210 $modulePrefix = "($modulePrefix) ";
1213 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1216 private $mCanApiHighLimits = null;
1219 * Check whether the current user is allowed to use high limits
1222 public function canApiHighLimits() {
1223 if ( !isset( $this->mCanApiHighLimits
) ) {
1224 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1227 return $this->mCanApiHighLimits
;
1231 * Check whether the user wants us to show version information in the API help
1233 * @deprecated since 1.21, always returns false
1235 public function getShowVersions() {
1236 wfDeprecated( __METHOD__
, '1.21' );
1241 * Overrides to return this instance's module manager.
1242 * @return ApiModuleManager
1244 public function getModuleManager() {
1245 return $this->mModuleMgr
;
1249 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1250 * classes who wish to add their own modules to their lexicon or override the
1251 * behavior of inherent ones.
1253 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1254 * @param string $name The identifier for this module.
1255 * @param $class ApiBase The class where this module is implemented.
1257 protected function addModule( $name, $class ) {
1258 $this->getModuleManager()->addModule( $name, 'action', $class );
1262 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1263 * classes who wish to add to or modify current formatters.
1265 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1266 * @param string $name The identifier for this format.
1267 * @param $class ApiFormatBase The class implementing this format.
1269 protected function addFormat( $name, $class ) {
1270 $this->getModuleManager()->addModule( $name, 'format', $class );
1274 * Get the array mapping module names to class names
1275 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1278 function getModules() {
1279 return $this->getModuleManager()->getNamesWithClasses( 'action' );
1283 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1286 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1289 public function getFormats() {
1290 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1295 * This exception will be thrown when dieUsage is called to stop module execution.
1296 * The exception handling code will print a help screen explaining how this API may be used.
1300 class UsageException
extends MWException
{
1307 private $mExtraData;
1310 * @param $message string
1311 * @param $codestr string
1313 * @param $extradata array|null
1315 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1316 parent
::__construct( $message, $code );
1317 $this->mCodestr
= $codestr;
1318 $this->mExtraData
= $extradata;
1324 public function getCodeString() {
1325 return $this->mCodestr
;
1331 public function getMessageArray() {
1333 'code' => $this->mCodestr
,
1334 'info' => $this->getMessage()
1336 if ( is_array( $this->mExtraData
) ) {
1337 $result = array_merge( $result, $this->mExtraData
);
1345 public function __toString() {
1346 return "{$this->getCodeString()}: {$this->getMessage()}";