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',
89 * List of available formats: format name => format class
91 private static $Formats = array(
92 'json' => 'ApiFormatJson',
93 'jsonfm' => 'ApiFormatJson',
94 'php' => 'ApiFormatPhp',
95 'phpfm' => 'ApiFormatPhp',
96 'wddx' => 'ApiFormatWddx',
97 'wddxfm' => 'ApiFormatWddx',
98 'xml' => 'ApiFormatXml',
99 'xmlfm' => 'ApiFormatXml',
100 'yaml' => 'ApiFormatYaml',
101 'yamlfm' => 'ApiFormatYaml',
102 'rawfm' => 'ApiFormatJson',
103 'txt' => 'ApiFormatTxt',
104 'txtfm' => 'ApiFormatTxt',
105 'dbg' => 'ApiFormatDbg',
106 'dbgfm' => 'ApiFormatDbg',
107 'dump' => 'ApiFormatDump',
108 'dumpfm' => 'ApiFormatDump',
109 'none' => 'ApiFormatNone',
113 * List of user roles that are specifically relevant to the API.
114 * array( 'right' => array ( 'msg' => 'Some message with a $1',
115 * 'params' => array ( $someVarToSubst ) ),
118 private static $mRights = array(
120 'msg' => 'Use of the write API',
123 'apihighlimits' => array(
124 '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.',
125 'params' => array( ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
)
134 private $mModuleMgr, $mResult;
136 private $mEnableWrite;
137 private $mInternalMode, $mSquidMaxage, $mModule;
139 private $mCacheMode = 'private';
140 private $mCacheControl = array();
141 private $mParamsUsed = array();
144 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
146 * @param $context IContextSource|WebRequest - if this is an instance of FauxRequest, errors are thrown and no printing occurs
147 * @param $enableWrite bool should be set to true if the api may modify data
149 public function __construct( $context = null, $enableWrite = false ) {
150 if ( $context === null ) {
151 $context = RequestContext
::getMain();
152 } elseif ( $context instanceof WebRequest
) {
155 $context = RequestContext
::getMain();
157 // We set a derivative context so we can change stuff later
158 $this->setContext( new DerivativeContext( $context ) );
160 if ( isset( $request ) ) {
161 $this->getContext()->setRequest( $request );
164 $this->mInternalMode
= ( $this->getRequest() instanceof FauxRequest
);
166 // Special handling for the main module: $parent === $this
167 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
169 if ( !$this->mInternalMode
) {
170 // Impose module restrictions.
171 // If the current user cannot read,
172 // Remove all modules other than login
175 if ( $this->getVal( 'callback' ) !== null ) {
176 // JSON callback allows cross-site reads.
177 // For safety, strip user credentials.
178 wfDebug( "API: stripping user credentials for JSON callback\n" );
179 $wgUser = new User();
180 $this->getContext()->setUser( $wgUser );
184 global $wgAPIModules;
185 $this->mModuleMgr
= new ApiModuleManager( $this );
186 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
187 $this->mModuleMgr
->addModules( $wgAPIModules, 'action' );
188 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
190 $this->mResult
= new ApiResult( $this );
191 $this->mEnableWrite
= $enableWrite;
193 $this->mSquidMaxage
= - 1; // flag for executeActionWithErrorHandling()
194 $this->mCommit
= false;
198 * Return true if the API was started by other PHP code using FauxRequest
201 public function isInternalMode() {
202 return $this->mInternalMode
;
206 * Get the ApiResult object associated with current request
210 public function getResult() {
211 return $this->mResult
;
215 * Get the API module object. Only works after executeAction()
219 public function getModule() {
220 return $this->mModule
;
224 * Get the result formatter object. Only works after setupExecuteAction()
226 * @return ApiFormatBase
228 public function getPrinter() {
229 return $this->mPrinter
;
233 * Set how long the response should be cached.
237 public function setCacheMaxAge( $maxage ) {
238 $this->setCacheControl( array(
239 'max-age' => $maxage,
240 's-maxage' => $maxage
245 * Set the type of caching headers which will be sent.
247 * @param $mode String One of:
248 * - 'public': Cache this object in public caches, if the maxage or smaxage
249 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
250 * not provided by any of these means, the object will be private.
251 * - 'private': Cache this object only in private client-side caches.
252 * - 'anon-public-user-private': Make this object cacheable for logged-out
253 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
254 * set consistently for a given URL, it cannot be set differently depending on
255 * things like the contents of the database, or whether the user is logged in.
257 * If the wiki does not allow anonymous users to read it, the mode set here
258 * will be ignored, and private caching headers will always be sent. In other words,
259 * the "public" mode is equivalent to saying that the data sent is as public as a page
262 * For user-dependent data, the private mode should generally be used. The
263 * anon-public-user-private mode should only be used where there is a particularly
264 * good performance reason for caching the anonymous response, but where the
265 * response to logged-in users may differ, or may contain private data.
267 * If this function is never called, then the default will be the private mode.
269 public function setCacheMode( $mode ) {
270 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
271 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
272 // Ignore for forwards-compatibility
276 if ( !in_array( 'read', User
::getGroupPermissions( array( '*' ) ), true ) ) {
277 // Private wiki, only private headers
278 if ( $mode !== 'private' ) {
279 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
284 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
285 $this->mCacheMode
= $mode;
289 * @deprecated since 1.17 Private caching is now the default, so there is usually no
290 * need to call this function. If there is a need, you can use
291 * $this->setCacheMode('private')
293 public function setCachePrivate() {
294 wfDeprecated( __METHOD__
, '1.17' );
295 $this->setCacheMode( 'private' );
299 * Set directives (key/value pairs) for the Cache-Control header.
300 * Boolean values will be formatted as such, by including or omitting
301 * without an equals sign.
303 * Cache control values set here will only be used if the cache mode is not
304 * private, see setCacheMode().
306 * @param $directives array
308 public function setCacheControl( $directives ) {
309 $this->mCacheControl
= $directives +
$this->mCacheControl
;
313 * Make sure Vary: Cookie and friends are set. Use this when the output of a request
314 * may be cached for anons but may not be cached for logged-in users.
316 * WARNING: This function must be called CONSISTENTLY for a given URL. This means that a
317 * given URL must either always or never call this function; if it sometimes does and
318 * sometimes doesn't, stuff will break.
320 * @deprecated since 1.17 Use setCacheMode( 'anon-public-user-private' )
322 public function setVaryCookie() {
323 wfDeprecated( __METHOD__
, '1.17' );
324 $this->setCacheMode( 'anon-public-user-private' );
328 * Create an instance of an output formatter by its name
330 * @param $format string
332 * @return ApiFormatBase
334 public function createPrinterByName( $format ) {
335 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
336 if ( $printer === null ) {
337 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
343 * Execute api request. Any errors will be handled if the API was called by the remote client.
345 public function execute() {
347 if ( $this->mInternalMode
) {
348 $this->executeAction();
350 $this->executeActionWithErrorHandling();
357 * Execute an action, and in case of an error, erase whatever partial results
358 * have been accumulated, and replace it with an error message and a help screen.
360 protected function executeActionWithErrorHandling() {
361 // Verify the CORS header before executing the action
362 if ( !$this->handleCORS() ) {
363 // handleCORS() has sent a 403, abort
367 // In case an error occurs during data output,
368 // clear the output buffer and print just the error information
371 $t = microtime( true );
373 $this->executeAction();
374 } catch ( Exception
$e ) {
375 // Allow extra cleanup and logging
376 wfRunHooks( 'ApiMain::onException', array( $this, $e ) );
379 if ( $e instanceof MWException
&& !( $e instanceof UsageException
) ) {
380 global $wgLogExceptionBacktrace;
381 if ( $wgLogExceptionBacktrace ) {
382 wfDebugLog( 'exception', $e->getLogMessage() . "\n" . $e->getTraceAsString() . "\n" );
384 wfDebugLog( 'exception', $e->getLogMessage() );
388 // Handle any kind of exception by outputting properly formatted error message.
389 // If this fails, an unhandled exception should be thrown so that global error
390 // handler will process and log it.
392 $errCode = $this->substituteResultWithError( $e );
394 // Error results should not be cached
395 $this->setCacheMode( 'private' );
397 $response = $this->getRequest()->response();
398 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
399 if ( $e->getCode() === 0 ) {
400 $response->header( $headerStr );
402 $response->header( $headerStr, true, $e->getCode() );
405 // Reset and print just the error message
408 // If the error occurred during printing, do a printer->profileOut()
409 $this->mPrinter
->safeProfileOut();
410 $this->printResult( true );
413 // Log the request whether or not there was an error
414 $this->logRequest( microtime( true ) - $t);
416 // Send cache headers after any code which might generate an error, to
417 // avoid sending public cache headers for errors.
418 $this->sendCacheHeaders();
420 if ( $this->mPrinter
->getIsHtml() && !$this->mPrinter
->isDisabled() ) {
428 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
430 * If no origin parameter is present, nothing happens.
431 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
432 * is set and false is returned.
433 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
434 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
437 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
439 protected function handleCORS() {
440 global $wgCrossSiteAJAXdomains, $wgCrossSiteAJAXdomainExceptions;
442 $originParam = $this->getParameter( 'origin' ); // defaults to null
443 if ( $originParam === null ) {
444 // No origin parameter, nothing to do
448 $request = $this->getRequest();
449 $response = $request->response();
450 // Origin: header is a space-separated list of origins, check all of them
451 $originHeader = $request->getHeader( 'Origin' );
452 if ( $originHeader === false ) {
455 $origins = explode( ' ', $originHeader );
457 if ( !in_array( $originParam, $origins ) ) {
458 // origin parameter set but incorrect
459 // Send a 403 response
460 $message = HttpStatus
::getMessage( 403 );
461 $response->header( "HTTP/1.1 403 $message", true, 403 );
462 $response->header( 'Cache-Control: no-cache' );
463 echo "'origin' parameter does not match Origin header\n";
466 if ( self
::matchOrigin( $originParam, $wgCrossSiteAJAXdomains, $wgCrossSiteAJAXdomainExceptions ) ) {
467 $response->header( "Access-Control-Allow-Origin: $originParam" );
468 $response->header( 'Access-Control-Allow-Credentials: true' );
469 $this->getOutput()->addVaryHeader( 'Origin' );
475 * Attempt to match an Origin header against a set of rules and a set of exceptions
476 * @param $value string Origin header
477 * @param $rules array Set of wildcard rules
478 * @param $exceptions array Set of wildcard rules
479 * @return bool True if $value matches a rule in $rules and doesn't match any rules in $exceptions, false otherwise
481 protected static function matchOrigin( $value, $rules, $exceptions ) {
482 foreach ( $rules as $rule ) {
483 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
484 // Rule matches, check exceptions
485 foreach ( $exceptions as $exc ) {
486 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
497 * Helper function to convert wildcard string into a regex
501 * @param $wildcard string String with wildcards
502 * @return string Regular expression
504 protected static function wildcardToRegex( $wildcard ) {
505 $wildcard = preg_quote( $wildcard, '/' );
506 $wildcard = str_replace(
511 return "/https?:\/\/$wildcard/";
514 protected function sendCacheHeaders() {
515 global $wgUseXVO, $wgVaryOnXFP;
516 $response = $this->getRequest()->response();
517 $out = $this->getOutput();
519 if ( $wgVaryOnXFP ) {
520 $out->addVaryHeader( 'X-Forwarded-Proto' );
523 if ( $this->mCacheMode
== 'private' ) {
524 $response->header( 'Cache-Control: private' );
528 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
529 $out->addVaryHeader( 'Cookie' );
530 $response->header( $out->getVaryHeader() );
532 $response->header( $out->getXVO() );
533 if ( $out->haveCacheVaryCookies() ) {
534 // Logged in, mark this request private
535 $response->header( 'Cache-Control: private' );
538 // Logged out, send normal public headers below
539 } elseif ( session_id() != '' ) {
540 // Logged in or otherwise has session (e.g. anonymous users who have edited)
541 // Mark request private
542 $response->header( 'Cache-Control: private' );
544 } // else no XVO and anonymous, send public headers below
547 // Send public headers
548 $response->header( $out->getVaryHeader() );
550 $response->header( $out->getXVO() );
553 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
554 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
555 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
557 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
558 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
561 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
562 // Public cache not requested
563 // Sending a Vary header in this case is harmless, and protects us
564 // against conditional calls of setCacheMaxAge().
565 $response->header( 'Cache-Control: private' );
569 $this->mCacheControl
['public'] = true;
571 // Send an Expires header
572 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
573 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
574 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
576 // Construct the Cache-Control header
579 foreach ( $this->mCacheControl
as $name => $value ) {
580 if ( is_bool( $value ) ) {
582 $ccHeader .= $separator . $name;
586 $ccHeader .= $separator . "$name=$value";
591 $response->header( "Cache-Control: $ccHeader" );
595 * Replace the result data with the information about an exception.
596 * Returns the error code
597 * @param $e Exception
600 protected function substituteResultWithError( $e ) {
601 global $wgShowHostnames;
603 $result = $this->getResult();
604 // Printer may not be initialized if the extractRequestParams() fails for the main module
605 if ( !isset ( $this->mPrinter
) ) {
606 // The printer has not been created yet. Try to manually get formatter value.
607 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
608 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
609 $value = self
::API_DEFAULT_FORMAT
;
612 $this->mPrinter
= $this->createPrinterByName( $value );
613 if ( $this->mPrinter
->getNeedsRawData() ) {
614 $result->setRawMode();
618 if ( $e instanceof UsageException
) {
619 // User entered incorrect parameters - print usage screen
620 $errMessage = $e->getMessageArray();
622 // Only print the help message when this is for the developer, not runtime
623 if ( $this->mPrinter
->getWantsHelp() ||
$this->mAction
== 'help' ) {
624 ApiResult
::setContent( $errMessage, $this->makeHelpMsg() );
627 global $wgShowSQLErrors, $wgShowExceptionDetails;
628 // Something is seriously wrong
629 if ( ( $e instanceof DBQueryError
) && !$wgShowSQLErrors ) {
630 $info = 'Database query error';
632 $info = "Exception Caught: {$e->getMessage()}";
636 'code' => 'internal_api_error_' . get_class( $e ),
639 ApiResult
::setContent( $errMessage, $wgShowExceptionDetails ?
"\n\n{$e->getTraceAsString()}\n\n" : '' );
642 // Remember all the warnings to re-add them later
643 $oldResult = $result->getData();
644 $warnings = isset( $oldResult['warnings'] ) ?
$oldResult['warnings'] : null;
647 $result->disableSizeCheck();
649 $requestid = $this->getParameter( 'requestid' );
650 if ( !is_null( $requestid ) ) {
651 $result->addValue( null, 'requestid', $requestid );
653 if ( $wgShowHostnames ) {
654 // servedby is especially useful when debugging errors
655 $result->addValue( null, 'servedby', wfHostName() );
657 if ( $warnings !== null ) {
658 $result->addValue( null, 'warnings', $warnings );
661 $result->addValue( null, 'error', $errMessage );
663 return $errMessage['code'];
667 * Set up for the execution.
670 protected function setupExecuteAction() {
671 global $wgShowHostnames;
673 // First add the id to the top element
674 $result = $this->getResult();
675 $requestid = $this->getParameter( 'requestid' );
676 if ( !is_null( $requestid ) ) {
677 $result->addValue( null, 'requestid', $requestid );
680 if ( $wgShowHostnames ) {
681 $servedby = $this->getParameter( 'servedby' );
683 $result->addValue( null, 'servedby', wfHostName() );
687 $params = $this->extractRequestParams();
689 $this->mAction
= $params['action'];
691 if ( !is_string( $this->mAction
) ) {
692 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
699 * Set up the module for response
700 * @return ApiBase The module that will handle this action
702 protected function setupModule() {
703 // Instantiate the module requested by the user
704 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
705 if ( $module === null ) {
706 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
708 $moduleParams = $module->extractRequestParams();
710 // Die if token required, but not provided (unless there is a gettoken parameter)
711 if ( isset( $moduleParams['gettoken'] ) ) {
712 $gettoken = $moduleParams['gettoken'];
717 $salt = $module->getTokenSalt();
718 if ( $salt !== false && !$gettoken ) {
719 if ( !isset( $moduleParams['token'] ) ) {
720 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
722 if ( !$this->getUser()->matchEditToken( $moduleParams['token'], $salt, $this->getContext()->getRequest() ) ) {
723 $this->dieUsageMsg( 'sessionfailure' );
731 * Check the max lag if necessary
732 * @param $module ApiBase object: Api module being used
733 * @param $params Array an array containing the request parameters.
734 * @return boolean True on success, false should exit immediately
736 protected function checkMaxLag( $module, $params ) {
737 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
739 global $wgShowHostnames;
740 $maxLag = $params['maxlag'];
741 list( $host, $lag ) = wfGetLB()->getMaxLag();
742 if ( $lag > $maxLag ) {
743 $response = $this->getRequest()->response();
745 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
746 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
748 if ( $wgShowHostnames ) {
749 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
751 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
760 * Check for sufficient permissions to execute
761 * @param $module ApiBase An Api module
763 protected function checkExecutePermissions( $module ) {
764 $user = $this->getUser();
765 if ( $module->isReadMode() && !in_array( 'read', User
::getGroupPermissions( array( '*' ) ), true ) &&
766 !$user->isAllowed( 'read' ) )
768 $this->dieUsageMsg( 'readrequired' );
770 if ( $module->isWriteMode() ) {
771 if ( !$this->mEnableWrite
) {
772 $this->dieUsageMsg( 'writedisabled' );
774 if ( !$user->isAllowed( 'writeapi' ) ) {
775 $this->dieUsageMsg( 'writerequired' );
777 if ( wfReadOnly() ) {
778 $this->dieReadOnly();
782 // Allow extensions to stop execution for arbitrary reasons.
784 if( !wfRunHooks( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
785 $this->dieUsageMsg( $message );
790 * Check POST for external response and setup result printer
791 * @param $module ApiBase An Api module
792 * @param $params Array an array with the request parameters
794 protected function setupExternalResponse( $module, $params ) {
795 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
796 // Module requires POST. GET request might still be allowed
797 // if $wgDebugApi is true, otherwise fail.
798 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction
) );
801 // See if custom printer is used
802 $this->mPrinter
= $module->getCustomPrinter();
803 if ( is_null( $this->mPrinter
) ) {
804 // Create an appropriate printer
805 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
808 if ( $this->mPrinter
->getNeedsRawData() ) {
809 $this->getResult()->setRawMode();
814 * Execute the actual module, without any error handling
816 protected function executeAction() {
817 $params = $this->setupExecuteAction();
818 $module = $this->setupModule();
819 $this->mModule
= $module;
821 $this->checkExecutePermissions( $module );
823 if ( !$this->checkMaxLag( $module, $params ) ) {
827 if ( !$this->mInternalMode
) {
828 $this->setupExternalResponse( $module, $params );
832 $module->profileIn();
834 wfRunHooks( 'APIAfterExecute', array( &$module ) );
835 $module->profileOut();
837 if ( !$this->mInternalMode
) {
838 // Report unused params
839 $this->reportUnusedParams();
841 //append Debug information
842 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
845 $this->printResult( false );
850 * Log the preceding request
851 * @param $time Time in seconds
853 protected function logRequest( $time ) {
854 $request = $this->getRequest();
855 $milliseconds = $time === null ?
'?' : round( $time * 1000 );
857 ' ' . $request->getMethod() .
858 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
859 ' ' . $request->getIP() .
860 ' T=' . $milliseconds .'ms';
861 foreach ( $this->getParamsUsed() as $name ) {
862 $value = $request->getVal( $name );
863 if ( $value === null ) {
866 $s .= ' ' . $name . '=';
867 if ( strlen( $value ) > 256 ) {
868 $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
869 $s .= $encValue . '[...]';
871 $s .= $this->encodeRequestLogValue( $value );
875 wfDebugLog( 'api', $s, false );
879 * Encode a value in a format suitable for a space-separated log line.
881 protected function encodeRequestLogValue( $s ) {
884 $chars = ';@$!*(),/:';
885 for ( $i = 0; $i < strlen( $chars ); $i++
) {
886 $table[rawurlencode( $chars[$i] )] = $chars[$i];
889 return strtr( rawurlencode( $s ), $table );
893 * Get the request parameters used in the course of the preceding execute() request
895 protected function getParamsUsed() {
896 return array_keys( $this->mParamsUsed
);
900 * Get a request value, and register the fact that it was used, for logging.
902 public function getVal( $name, $default = null ) {
903 $this->mParamsUsed
[$name] = true;
904 return $this->getRequest()->getVal( $name, $default );
908 * Get a boolean request value, and register the fact that the parameter
909 * was used, for logging.
911 public function getCheck( $name ) {
912 $this->mParamsUsed
[$name] = true;
913 return $this->getRequest()->getCheck( $name );
917 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
918 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
920 protected function reportUnusedParams() {
921 $paramsUsed = $this->getParamsUsed();
922 $allParams = $this->getRequest()->getValueNames();
924 $unusedParams = array_diff( $allParams, $paramsUsed );
925 if( count( $unusedParams ) ) {
926 $s = count( $unusedParams ) > 1 ?
's' : '';
927 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
932 * Print results using the current printer
934 * @param $isError bool
936 protected function printResult( $isError ) {
938 if( $wgDebugAPI !== false ) {
939 $this->getResult()->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
942 $this->getResult()->cleanUpUTF8();
943 $printer = $this->mPrinter
;
944 $printer->profileIn();
947 * If the help message is requested in the default (xmlfm) format,
948 * tell the printer not to escape ampersands so that our links do
951 $printer->setUnescapeAmps( ( $this->mAction
== 'help' ||
$isError )
952 && $printer->getFormat() == 'XML' && $printer->getIsHtml() );
954 $printer->initPrinter( $isError );
957 $printer->closePrinter();
958 $printer->profileOut();
964 public function isReadMode() {
969 * See ApiBase for description.
973 public function getAllowedParams() {
976 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
977 ApiBase
::PARAM_TYPE
=> $this->mModuleMgr
->getNames( 'format' )
980 ApiBase
::PARAM_DFLT
=> 'help',
981 ApiBase
::PARAM_TYPE
=> $this->mModuleMgr
->getNames( 'action' )
984 ApiBase
::PARAM_TYPE
=> 'integer'
987 ApiBase
::PARAM_TYPE
=> 'integer',
988 ApiBase
::PARAM_DFLT
=> 0
991 ApiBase
::PARAM_TYPE
=> 'integer',
992 ApiBase
::PARAM_DFLT
=> 0
1001 * See ApiBase for description.
1005 public function getParamDescription() {
1007 'format' => 'The format of the output',
1008 'action' => 'What action you would like to perform. See below for module help',
1010 'Maximum lag can be used when MediaWiki is installed on a database replicated cluster.',
1011 'To save actions causing any more site replication lag, this parameter can make the client',
1012 'wait until the replication lag is less than the specified value.',
1013 'In case of a replag error, error code "maxlag" is returned, with the message like',
1014 '"Waiting for $host: $lag seconds lagged\n".',
1015 'See https://www.mediawiki.org/wiki/Manual:Maxlag_parameter for more information',
1017 'smaxage' => 'Set the s-maxage header to this many seconds. Errors are never cached',
1018 'maxage' => 'Set the max-age header to this many seconds. Errors are never cached',
1019 'requestid' => 'Request ID to distinguish requests. This will just be output back to you',
1020 'servedby' => 'Include the hostname that served the request in the results. Unconditionally shown on error',
1022 'When accessing the API using a cross-domain AJAX request (CORS), set this to the originating domain.',
1023 '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 .',
1024 'If this parameter does not match the Origin: header, a 403 response will be returned.',
1025 'If this parameter matches the Origin: header and the origin is whitelisted, an Access-Control-Allow-Origin header will be set.',
1031 * See ApiBase for description.
1035 public function getDescription() {
1039 '**********************************************************************************************************',
1041 '** This is an auto-generated MediaWiki API documentation page **',
1043 '** Documentation and Examples: **',
1044 '** https://www.mediawiki.org/wiki/API **',
1046 '**********************************************************************************************************',
1048 'Status: All features shown on this page should be working, but the API',
1049 ' is still in active development, and may change at any time.',
1050 ' Make sure to monitor our mailing list for any updates',
1052 'Erroneous requests: When erroneous requests are sent to the API, a HTTP header will be sent',
1053 ' with the key "MediaWiki-API-Error" and then both the value of the',
1054 ' header and the error code sent back will be set to the same value',
1056 ' In the case of an invalid action being passed, these will have a value',
1057 ' of "unknown_action"',
1059 ' For more information see https://www.mediawiki.org/wiki/API:Errors_and_warnings',
1061 'Documentation: https://www.mediawiki.org/wiki/API:Main_page',
1062 'FAQ https://www.mediawiki.org/wiki/API:FAQ',
1063 'Mailing list: https://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
1064 'Api Announcements: https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce',
1065 'Bugs & Requests: https://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
1077 public function getPossibleErrors() {
1078 return array_merge( parent
::getPossibleErrors(), array(
1079 array( 'readonlytext' ),
1080 array( 'code' => 'unknown_format', 'info' => 'Unrecognized format: format' ),
1081 array( 'code' => 'unknown_action', 'info' => 'The API requires a valid action parameter' ),
1082 array( 'code' => 'maxlag', 'info' => 'Waiting for host: x seconds lagged' ),
1083 array( 'code' => 'maxlag', 'info' => 'Waiting for a database server: x seconds lagged' ),
1088 * Returns an array of strings with credits for the API
1091 protected function getCredits() {
1094 ' Roan Kattouw "<Firstname>.<Lastname>@gmail.com" (lead developer Sep 2007-present)',
1095 ' Victor Vasiliev - vasilvv at gee mail dot com',
1096 ' Bryan Tong Minh - bryan . tongminh @ gmail . com',
1097 ' Sam Reed - sam @ reedyboy . net',
1098 ' Yuri Astrakhan "<Firstname><Lastname>@gmail.com" (creator, lead developer Sep 2006-Sep 2007, 2012)',
1100 'Please send your comments, suggestions and questions to mediawiki-api@lists.wikimedia.org',
1101 'or file a bug report at https://bugzilla.wikimedia.org/'
1106 * Sets whether the pretty-printer should format *bold* and $italics$
1110 public function setHelp( $help = true ) {
1111 $this->mPrinter
->setHelp( $help );
1115 * Override the parent to generate help messages for all available modules.
1119 public function makeHelpMsg() {
1120 global $wgMemc, $wgAPICacheHelpTimeout;
1122 // Get help text from cache if present
1123 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1124 SpecialVersion
::getVersion( 'nodb' ) );
1125 if ( $wgAPICacheHelpTimeout > 0 ) {
1126 $cached = $wgMemc->get( $key );
1131 $retval = $this->reallyMakeHelpMsg();
1132 if ( $wgAPICacheHelpTimeout > 0 ) {
1133 $wgMemc->set( $key, $retval, $wgAPICacheHelpTimeout );
1139 * @return mixed|string
1141 public function reallyMakeHelpMsg() {
1144 // Use parent to make default message for the main module
1145 $msg = parent
::makeHelpMsg();
1147 $astriks = str_repeat( '*** ', 14 );
1148 $msg .= "\n\n$astriks Modules $astriks\n\n";
1150 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1151 $module = $this->mModuleMgr
->getModule( $name );
1152 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1154 $msg2 = $module->makeHelpMsg();
1155 if ( $msg2 !== false ) {
1161 $msg .= "\n$astriks Permissions $astriks\n\n";
1162 foreach ( self
::$mRights as $right => $rightMsg ) {
1163 $groups = User
::getGroupsWithPermission( $right );
1164 $msg .= "* " . $right . " *\n " . wfMsgReplaceArgs( $rightMsg['msg'], $rightMsg['params'] ) .
1165 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1168 $msg .= "\n$astriks Formats $astriks\n\n";
1169 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1170 $module = $this->mModuleMgr
->getModule( $name );
1171 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1172 $msg2 = $module->makeHelpMsg();
1173 if ( $msg2 !== false ) {
1179 $msg .= "\n*** Credits: ***\n " . implode( "\n ", $this->getCredits() ) . "\n";
1185 * @param $module ApiBase
1186 * @param $paramName String What type of request is this? e.g. action, query, list, prop, meta, format
1189 public static function makeHelpMsgHeader( $module, $paramName ) {
1190 $modulePrefix = $module->getModulePrefix();
1191 if ( strval( $modulePrefix ) !== '' ) {
1192 $modulePrefix = "($modulePrefix) ";
1195 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1198 private $mCanApiHighLimits = null;
1201 * Check whether the current user is allowed to use high limits
1204 public function canApiHighLimits() {
1205 if ( !isset( $this->mCanApiHighLimits
) ) {
1206 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1209 return $this->mCanApiHighLimits
;
1213 * Check whether the user wants us to show version information in the API help
1215 * @deprecated since 1.21, always returns false
1217 public function getShowVersions() {
1218 wfDeprecated( __METHOD__
, '1.21' );
1223 * Overrides to return this instance's module manager.
1224 * @return ApiModuleManager
1226 public function getModuleManager() {
1227 return $this->mModuleMgr
;
1231 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1232 * classes who wish to add their own modules to their lexicon or override the
1233 * behavior of inherent ones.
1235 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1236 * @param $name string The identifier for this module.
1237 * @param $class ApiBase The class where this module is implemented.
1239 protected function addModule( $name, $class ) {
1240 $this->getModuleManager()->addModule( $name, 'action', $class );
1244 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1245 * classes who wish to add to or modify current formatters.
1247 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1248 * @param $name string The identifier for this format.
1249 * @param $class ApiFormatBase The class implementing this format.
1251 protected function addFormat( $name, $class ) {
1252 $this->getModuleManager
->addModule( $name, 'format', $class );
1256 * Get the array mapping module names to class names
1257 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1260 function getModules() {
1261 return $this->getModuleManager()->getNamesWithClasses( 'action' );
1265 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1268 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1271 public function getFormats() {
1272 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1277 * This exception will be thrown when dieUsage is called to stop module execution.
1278 * The exception handling code will print a help screen explaining how this API may be used.
1282 class UsageException
extends MWException
{
1289 private $mExtraData;
1292 * @param $message string
1293 * @param $codestr string
1295 * @param $extradata array|null
1297 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1298 parent
::__construct( $message, $code );
1299 $this->mCodestr
= $codestr;
1300 $this->mExtraData
= $extradata;
1306 public function getCodeString() {
1307 return $this->mCodestr
;
1313 public function getMessageArray() {
1315 'code' => $this->mCodestr
,
1316 'info' => $this->getMessage()
1318 if ( is_array( $this->mExtraData
) ) {
1319 $result = array_merge( $result, $this->mExtraData
);
1327 public function __toString() {
1328 return "{$this->getCodeString()}: {$this->getMessage()}";