5 * Created on Sep 4, 2006
7 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
29 * This is the main API class, used for both external and internal processing.
30 * When executed, it will create the requested formatter object,
31 * instantiate and execute an object associated with the needed action,
32 * and use formatter to print results.
33 * In case of an exception, an error message will be printed using the same formatter.
35 * To use API from another application, run it using FauxRequest object, in which
36 * case any internal exceptions will not be handled but passed up to the caller.
37 * After successful execution, use getResult() for the resulting data.
41 class ApiMain
extends ApiBase
{
43 * When no format parameter is given, this format will be used
45 const API_DEFAULT_FORMAT
= 'jsonfm';
48 * List of available modules: action name => module class
50 private static $Modules = array(
51 'login' => 'ApiLogin',
52 'logout' => 'ApiLogout',
53 'createaccount' => 'ApiCreateAccount',
54 'query' => 'ApiQuery',
55 'expandtemplates' => 'ApiExpandTemplates',
56 'parse' => 'ApiParse',
57 'stashedit' => 'ApiStashEdit',
58 'opensearch' => 'ApiOpenSearch',
59 'feedcontributions' => 'ApiFeedContributions',
60 'feedrecentchanges' => 'ApiFeedRecentChanges',
61 'feedwatchlist' => 'ApiFeedWatchlist',
63 'paraminfo' => 'ApiParamInfo',
65 'compare' => 'ApiComparePages',
66 'tokens' => 'ApiTokens',
69 'purge' => 'ApiPurge',
70 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
71 'rollback' => 'ApiRollback',
72 'delete' => 'ApiDelete',
73 'undelete' => 'ApiUndelete',
74 'protect' => 'ApiProtect',
75 'block' => 'ApiBlock',
76 'unblock' => 'ApiUnblock',
78 'edit' => 'ApiEditPage',
79 'upload' => 'ApiUpload',
80 'filerevert' => 'ApiFileRevert',
81 'emailuser' => 'ApiEmailUser',
82 'watch' => 'ApiWatch',
83 'patrol' => 'ApiPatrol',
84 'import' => 'ApiImport',
85 'clearhasmsg' => 'ApiClearHasMsg',
86 'userrights' => 'ApiUserrights',
87 'options' => 'ApiOptions',
88 'imagerotate' => 'ApiImageRotate',
89 'revisiondelete' => 'ApiRevisionDelete',
90 'managetags' => 'ApiManageTags',
94 * List of available formats: format name => format class
96 private static $Formats = array(
97 'json' => 'ApiFormatJson',
98 'jsonfm' => 'ApiFormatJson',
99 'php' => 'ApiFormatPhp',
100 'phpfm' => 'ApiFormatPhp',
101 'wddx' => 'ApiFormatWddx',
102 'wddxfm' => 'ApiFormatWddx',
103 'xml' => 'ApiFormatXml',
104 'xmlfm' => 'ApiFormatXml',
105 'yaml' => 'ApiFormatYaml',
106 'yamlfm' => 'ApiFormatYaml',
107 'rawfm' => 'ApiFormatJson',
108 'txt' => 'ApiFormatTxt',
109 'txtfm' => 'ApiFormatTxt',
110 'dbg' => 'ApiFormatDbg',
111 'dbgfm' => 'ApiFormatDbg',
112 'dump' => 'ApiFormatDump',
113 'dumpfm' => 'ApiFormatDump',
114 'none' => 'ApiFormatNone',
117 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
119 * List of user roles that are specifically relevant to the API.
120 * array( 'right' => array ( 'msg' => 'Some message with a $1',
121 * 'params' => array ( $someVarToSubst ) ),
124 private static $mRights = array(
126 'msg' => 'right-writeapi',
129 'apihighlimits' => array(
130 'msg' => 'api-help-right-apihighlimits',
131 'params' => array( ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
)
134 // @codingStandardsIgnoreEnd
141 private $mModuleMgr, $mResult;
143 private $mEnableWrite;
144 private $mInternalMode, $mSquidMaxage, $mModule;
146 private $mCacheMode = 'private';
147 private $mCacheControl = array();
148 private $mParamsUsed = array();
151 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
153 * @param IContextSource|WebRequest $context If this is an instance of
154 * FauxRequest, errors are thrown and no printing occurs
155 * @param bool $enableWrite Should be set to true if the api may modify data
157 public function __construct( $context = null, $enableWrite = false ) {
158 if ( $context === null ) {
159 $context = RequestContext
::getMain();
160 } elseif ( $context instanceof WebRequest
) {
163 $context = RequestContext
::getMain();
165 // We set a derivative context so we can change stuff later
166 $this->setContext( new DerivativeContext( $context ) );
168 if ( isset( $request ) ) {
169 $this->getContext()->setRequest( $request );
172 $this->mInternalMode
= ( $this->getRequest() instanceof FauxRequest
);
174 // Special handling for the main module: $parent === $this
175 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
177 if ( !$this->mInternalMode
) {
178 // Impose module restrictions.
179 // If the current user cannot read,
180 // Remove all modules other than login
183 if ( $this->getVal( 'callback' ) !== null ) {
184 // JSON callback allows cross-site reads.
185 // For safety, strip user credentials.
186 wfDebug( "API: stripping user credentials for JSON callback\n" );
187 $wgUser = new User();
188 $this->getContext()->setUser( $wgUser );
192 $uselang = $this->getParameter( 'uselang' );
193 if ( $uselang === 'user' ) {
194 // Assume the parent context is going to return the user language
195 // for uselang=user (see T85635).
197 if ( $uselang === 'content' ) {
199 $uselang = $wgContLang->getCode();
201 $code = RequestContext
::sanitizeLangCode( $uselang );
202 $this->getContext()->setLanguage( $code );
203 if ( !$this->mInternalMode
) {
205 $wgLang = $this->getContext()->getLanguage();
206 RequestContext
::getMain()->setLanguage( $wgLang );
210 $config = $this->getConfig();
211 $this->mModuleMgr
= new ApiModuleManager( $this );
212 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
213 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
214 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
215 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
217 $this->mResult
= new ApiResult( $this );
218 $this->mEnableWrite
= $enableWrite;
220 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
221 $this->mCommit
= false;
225 * Return true if the API was started by other PHP code using FauxRequest
228 public function isInternalMode() {
229 return $this->mInternalMode
;
233 * Get the ApiResult object associated with current request
237 public function getResult() {
238 return $this->mResult
;
242 * Get the API module object. Only works after executeAction()
246 public function getModule() {
247 return $this->mModule
;
251 * Get the result formatter object. Only works after setupExecuteAction()
253 * @return ApiFormatBase
255 public function getPrinter() {
256 return $this->mPrinter
;
260 * Set how long the response should be cached.
264 public function setCacheMaxAge( $maxage ) {
265 $this->setCacheControl( array(
266 'max-age' => $maxage,
267 's-maxage' => $maxage
272 * Set the type of caching headers which will be sent.
274 * @param string $mode One of:
275 * - 'public': Cache this object in public caches, if the maxage or smaxage
276 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
277 * not provided by any of these means, the object will be private.
278 * - 'private': Cache this object only in private client-side caches.
279 * - 'anon-public-user-private': Make this object cacheable for logged-out
280 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
281 * set consistently for a given URL, it cannot be set differently depending on
282 * things like the contents of the database, or whether the user is logged in.
284 * If the wiki does not allow anonymous users to read it, the mode set here
285 * will be ignored, and private caching headers will always be sent. In other words,
286 * the "public" mode is equivalent to saying that the data sent is as public as a page
289 * For user-dependent data, the private mode should generally be used. The
290 * anon-public-user-private mode should only be used where there is a particularly
291 * good performance reason for caching the anonymous response, but where the
292 * response to logged-in users may differ, or may contain private data.
294 * If this function is never called, then the default will be the private mode.
296 public function setCacheMode( $mode ) {
297 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
298 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
300 // Ignore for forwards-compatibility
304 if ( !User
::isEveryoneAllowed( 'read' ) ) {
305 // Private wiki, only private headers
306 if ( $mode !== 'private' ) {
307 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
313 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
314 // User language is used for i18n, so we don't want to publicly
315 // cache. Anons are ok, because if they have non-default language
316 // then there's an appropriate Vary header set by whatever set
317 // their non-default language.
318 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
319 "'anon-public-user-private' due to uselang=user\n" );
320 $mode = 'anon-public-user-private';
323 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
324 $this->mCacheMode
= $mode;
328 * Set directives (key/value pairs) for the Cache-Control header.
329 * Boolean values will be formatted as such, by including or omitting
330 * without an equals sign.
332 * Cache control values set here will only be used if the cache mode is not
333 * private, see setCacheMode().
335 * @param array $directives
337 public function setCacheControl( $directives ) {
338 $this->mCacheControl
= $directives +
$this->mCacheControl
;
342 * Create an instance of an output formatter by its name
344 * @param string $format
346 * @return ApiFormatBase
348 public function createPrinterByName( $format ) {
349 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
350 if ( $printer === null ) {
351 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
358 * Execute api request. Any errors will be handled if the API was called by the remote client.
360 public function execute() {
362 if ( $this->mInternalMode
) {
363 $this->executeAction();
365 $this->executeActionWithErrorHandling();
372 * Execute an action, and in case of an error, erase whatever partial results
373 * have been accumulated, and replace it with an error message and a help screen.
375 protected function executeActionWithErrorHandling() {
376 // Verify the CORS header before executing the action
377 if ( !$this->handleCORS() ) {
378 // handleCORS() has sent a 403, abort
382 // Exit here if the request method was OPTIONS
383 // (assume there will be a followup GET or POST)
384 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
388 // In case an error occurs during data output,
389 // clear the output buffer and print just the error information
392 $t = microtime( true );
394 $this->executeAction();
395 } catch ( Exception
$e ) {
396 $this->handleException( $e );
399 // Log the request whether or not there was an error
400 $this->logRequest( microtime( true ) - $t );
402 // Send cache headers after any code which might generate an error, to
403 // avoid sending public cache headers for errors.
404 $this->sendCacheHeaders();
410 * Handle an exception as an API response
413 * @param Exception $e
415 protected function handleException( Exception
$e ) {
416 // Bug 63145: Rollback any open database transactions
417 if ( !( $e instanceof UsageException
) ) {
418 // UsageExceptions are intentional, so don't rollback if that's the case
419 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
422 // Allow extra cleanup and logging
423 Hooks
::run( 'ApiMain::onException', array( $this, $e ) );
426 if ( !( $e instanceof UsageException
) ) {
427 MWExceptionHandler
::logException( $e );
430 // Handle any kind of exception by outputting properly formatted error message.
431 // If this fails, an unhandled exception should be thrown so that global error
432 // handler will process and log it.
434 $errCode = $this->substituteResultWithError( $e );
436 // Error results should not be cached
437 $this->setCacheMode( 'private' );
439 $response = $this->getRequest()->response();
440 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
441 if ( $e->getCode() === 0 ) {
442 $response->header( $headerStr );
444 $response->header( $headerStr, true, $e->getCode() );
447 // Reset and print just the error message
450 // If the error occurred during printing, do a printer->profileOut()
451 $this->mPrinter
->safeProfileOut();
452 $this->printResult( true );
456 * Handle an exception from the ApiBeforeMain hook.
458 * This tries to print the exception as an API response, to be more
459 * friendly to clients. If it fails, it will rethrow the exception.
462 * @param Exception $e
465 public static function handleApiBeforeMainException( Exception
$e ) {
469 $main = new self( RequestContext
::getMain(), false );
470 $main->handleException( $e );
471 } catch ( Exception
$e2 ) {
472 // Nope, even that didn't work. Punt.
476 // Log the request and reset cache headers
477 $main->logRequest( 0 );
478 $main->sendCacheHeaders();
484 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
486 * If no origin parameter is present, nothing happens.
487 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
488 * is set and false is returned.
489 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
490 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
492 * http://www.w3.org/TR/cors/#resource-requests
493 * http://www.w3.org/TR/cors/#resource-preflight-requests
495 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
497 protected function handleCORS() {
498 $originParam = $this->getParameter( 'origin' ); // defaults to null
499 if ( $originParam === null ) {
500 // No origin parameter, nothing to do
504 $request = $this->getRequest();
505 $response = $request->response();
507 // Origin: header is a space-separated list of origins, check all of them
508 $originHeader = $request->getHeader( 'Origin' );
509 if ( $originHeader === false ) {
512 $originHeader = trim( $originHeader );
513 $origins = preg_split( '/\s+/', $originHeader );
516 if ( !in_array( $originParam, $origins ) ) {
517 // origin parameter set but incorrect
518 // Send a 403 response
519 $message = HttpStatus
::getMessage( 403 );
520 $response->header( "HTTP/1.1 403 $message", true, 403 );
521 $response->header( 'Cache-Control: no-cache' );
522 echo "'origin' parameter does not match Origin header\n";
527 $config = $this->getConfig();
528 $matchOrigin = count( $origins ) === 1 && self
::matchOrigin(
530 $config->get( 'CrossSiteAJAXdomains' ),
531 $config->get( 'CrossSiteAJAXdomainExceptions' )
534 if ( $matchOrigin ) {
535 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
536 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
538 // This is a CORS preflight request
539 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
540 // If method is not a case-sensitive match, do not set any additional headers and terminate.
543 // We allow the actual request to send the following headers
544 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
545 if ( $requestedHeaders !== false ) {
546 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
549 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
552 // We only allow the actual request to be GET or POST
553 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
556 $response->header( "Access-Control-Allow-Origin: $originHeader" );
557 $response->header( 'Access-Control-Allow-Credentials: true' );
558 $response->header( "Timing-Allow-Origin: $originHeader" ); # http://www.w3.org/TR/resource-timing/#timing-allow-origin
561 $response->header( 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag' );
565 $this->getOutput()->addVaryHeader( 'Origin' );
570 * Attempt to match an Origin header against a set of rules and a set of exceptions
571 * @param string $value Origin header
572 * @param array $rules Set of wildcard rules
573 * @param array $exceptions Set of wildcard rules
574 * @return bool True if $value matches a rule in $rules and doesn't match
575 * any rules in $exceptions, false otherwise
577 protected static function matchOrigin( $value, $rules, $exceptions ) {
578 foreach ( $rules as $rule ) {
579 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
580 // Rule matches, check exceptions
581 foreach ( $exceptions as $exc ) {
582 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
595 * Attempt to validate the value of Access-Control-Request-Headers against a list
596 * of headers that we allow the follow up request to send.
598 * @param string $requestedHeaders Comma seperated list of HTTP headers
599 * @return bool True if all requested headers are in the list of allowed headers
601 protected static function matchRequestedHeaders( $requestedHeaders ) {
602 if ( trim( $requestedHeaders ) === '' ) {
605 $requestedHeaders = explode( ',', $requestedHeaders );
606 $allowedAuthorHeaders = array_flip( array(
607 /* simple headers (see spec) */
612 /* non-authorable headers in XHR, which are however requested by some UAs */
616 /* MediaWiki whitelist */
619 foreach ( $requestedHeaders as $rHeader ) {
620 $rHeader = strtolower( trim( $rHeader ) );
621 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
622 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
630 * Helper function to convert wildcard string into a regex
634 * @param string $wildcard String with wildcards
635 * @return string Regular expression
637 protected static function wildcardToRegex( $wildcard ) {
638 $wildcard = preg_quote( $wildcard, '/' );
639 $wildcard = str_replace(
645 return "/^https?:\/\/$wildcard$/";
648 protected function sendCacheHeaders() {
649 $response = $this->getRequest()->response();
650 $out = $this->getOutput();
652 $config = $this->getConfig();
654 if ( $config->get( 'VaryOnXFP' ) ) {
655 $out->addVaryHeader( 'X-Forwarded-Proto' );
658 if ( $this->mCacheMode
== 'private' ) {
659 $response->header( 'Cache-Control: private' );
663 $useXVO = $config->get( 'UseXVO' );
664 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
665 $out->addVaryHeader( 'Cookie' );
666 $response->header( $out->getVaryHeader() );
668 $response->header( $out->getXVO() );
669 if ( $out->haveCacheVaryCookies() ) {
670 // Logged in, mark this request private
671 $response->header( 'Cache-Control: private' );
674 // Logged out, send normal public headers below
675 } elseif ( session_id() != '' ) {
676 // Logged in or otherwise has session (e.g. anonymous users who have edited)
677 // Mark request private
678 $response->header( 'Cache-Control: private' );
681 } // else no XVO and anonymous, send public headers below
684 // Send public headers
685 $response->header( $out->getVaryHeader() );
687 $response->header( $out->getXVO() );
690 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
691 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
692 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
694 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
695 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
698 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
699 // Public cache not requested
700 // Sending a Vary header in this case is harmless, and protects us
701 // against conditional calls of setCacheMaxAge().
702 $response->header( 'Cache-Control: private' );
707 $this->mCacheControl
['public'] = true;
709 // Send an Expires header
710 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
711 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
712 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
714 // Construct the Cache-Control header
717 foreach ( $this->mCacheControl
as $name => $value ) {
718 if ( is_bool( $value ) ) {
720 $ccHeader .= $separator . $name;
724 $ccHeader .= $separator . "$name=$value";
729 $response->header( "Cache-Control: $ccHeader" );
733 * Replace the result data with the information about an exception.
734 * Returns the error code
735 * @param Exception $e
738 protected function substituteResultWithError( $e ) {
739 $result = $this->getResult();
741 // Printer may not be initialized if the extractRequestParams() fails for the main module
742 if ( !isset( $this->mPrinter
) ) {
743 // The printer has not been created yet. Try to manually get formatter value.
744 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
745 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
746 $value = self
::API_DEFAULT_FORMAT
;
749 $this->mPrinter
= $this->createPrinterByName( $value );
752 // Printer may not be able to handle errors. This is particularly
753 // likely if the module returns something for getCustomPrinter().
754 if ( !$this->mPrinter
->canPrintErrors() ) {
755 $this->mPrinter
->safeProfileOut();
756 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
759 // Update raw mode flag for the selected printer.
760 $result->setRawMode( $this->mPrinter
->getNeedsRawData() );
762 $config = $this->getConfig();
764 if ( $e instanceof UsageException
) {
765 // User entered incorrect parameters - generate error response
766 $errMessage = $e->getMessageArray();
767 $link = wfExpandUrl( wfScript( 'api' ) );
768 ApiResult
::setContent( $errMessage, "See $link for API usage" );
770 // Something is seriously wrong
771 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
772 $info = 'Database query error';
774 $info = "Exception Caught: {$e->getMessage()}";
778 'code' => 'internal_api_error_' . get_class( $e ),
779 'info' => '[' . MWExceptionHandler
::getLogId( $e ) . '] ' . $info,
781 if ( $config->get( 'ShowExceptionDetails' ) ) {
782 ApiResult
::setContent(
784 MWExceptionHandler
::getRedactedTraceAsString( $e )
789 // Remember all the warnings to re-add them later
790 $oldResult = $result->getData();
791 $warnings = isset( $oldResult['warnings'] ) ?
$oldResult['warnings'] : null;
795 $requestid = $this->getParameter( 'requestid' );
796 if ( !is_null( $requestid ) ) {
797 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
799 if ( $config->get( 'ShowHostnames' ) ) {
800 // servedby is especially useful when debugging errors
801 $result->addValue( null, 'servedby', wfHostName(), ApiResult
::NO_SIZE_CHECK
);
803 if ( $warnings !== null ) {
804 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
807 $result->addValue( null, 'error', $errMessage, ApiResult
::NO_SIZE_CHECK
);
809 return $errMessage['code'];
813 * Set up for the execution.
816 protected function setupExecuteAction() {
817 // First add the id to the top element
818 $result = $this->getResult();
819 $requestid = $this->getParameter( 'requestid' );
820 if ( !is_null( $requestid ) ) {
821 $result->addValue( null, 'requestid', $requestid );
824 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
825 $servedby = $this->getParameter( 'servedby' );
827 $result->addValue( null, 'servedby', wfHostName() );
831 if ( $this->getParameter( 'curtimestamp' ) ) {
832 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
833 ApiResult
::NO_SIZE_CHECK
);
836 $params = $this->extractRequestParams();
838 $this->mAction
= $params['action'];
840 if ( !is_string( $this->mAction
) ) {
841 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
848 * Set up the module for response
849 * @return ApiBase The module that will handle this action
850 * @throws MWException
851 * @throws UsageException
853 protected function setupModule() {
854 // Instantiate the module requested by the user
855 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
856 if ( $module === null ) {
857 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
859 $moduleParams = $module->extractRequestParams();
861 // Check token, if necessary
862 if ( $module->needsToken() === true ) {
863 throw new MWException(
864 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
865 "See documentation for ApiBase::needsToken for details."
868 if ( $module->needsToken() ) {
869 if ( !$module->mustBePosted() ) {
870 throw new MWException(
871 "Module '{$module->getModuleName()}' must require POST to use tokens."
875 if ( !isset( $moduleParams['token'] ) ) {
876 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
879 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
881 $module->encodeParamName( 'token' ),
882 $this->getRequest()->getQueryValues()
886 "The '{$module->encodeParamName( 'token' )}' parameter was found in the query string, but must be in the POST body",
891 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
892 $this->dieUsageMsg( 'sessionfailure' );
900 * Check the max lag if necessary
901 * @param ApiBase $module Api module being used
902 * @param array $params Array an array containing the request parameters.
903 * @return bool True on success, false should exit immediately
905 protected function checkMaxLag( $module, $params ) {
906 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
908 $maxLag = $params['maxlag'];
909 list( $host, $lag ) = wfGetLB()->getMaxLag();
910 if ( $lag > $maxLag ) {
911 $response = $this->getRequest()->response();
913 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
914 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
916 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
917 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
920 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
928 * Check for sufficient permissions to execute
929 * @param ApiBase $module An Api module
931 protected function checkExecutePermissions( $module ) {
932 $user = $this->getUser();
933 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
934 !$user->isAllowed( 'read' )
936 $this->dieUsageMsg( 'readrequired' );
938 if ( $module->isWriteMode() ) {
939 if ( !$this->mEnableWrite
) {
940 $this->dieUsageMsg( 'writedisabled' );
942 if ( !$user->isAllowed( 'writeapi' ) ) {
943 $this->dieUsageMsg( 'writerequired' );
945 if ( wfReadOnly() ) {
946 $this->dieReadOnly();
950 // Allow extensions to stop execution for arbitrary reasons.
952 if ( !Hooks
::run( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
953 $this->dieUsageMsg( $message );
958 * Check asserts of the user's rights
959 * @param array $params
961 protected function checkAsserts( $params ) {
962 if ( isset( $params['assert'] ) ) {
963 $user = $this->getUser();
964 switch ( $params['assert'] ) {
966 if ( $user->isAnon() ) {
967 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
971 if ( !$user->isAllowed( 'bot' ) ) {
972 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
980 * Check POST for external response and setup result printer
981 * @param ApiBase $module An Api module
982 * @param array $params An array with the request parameters
984 protected function setupExternalResponse( $module, $params ) {
985 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
986 // Module requires POST. GET request might still be allowed
987 // if $wgDebugApi is true, otherwise fail.
988 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction
) );
991 // See if custom printer is used
992 $this->mPrinter
= $module->getCustomPrinter();
993 if ( is_null( $this->mPrinter
) ) {
994 // Create an appropriate printer
995 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
998 if ( $this->mPrinter
->getNeedsRawData() ) {
999 $this->getResult()->setRawMode();
1004 * Execute the actual module, without any error handling
1006 protected function executeAction() {
1007 $params = $this->setupExecuteAction();
1008 $module = $this->setupModule();
1009 $this->mModule
= $module;
1011 $this->checkExecutePermissions( $module );
1013 if ( !$this->checkMaxLag( $module, $params ) ) {
1017 if ( !$this->mInternalMode
) {
1018 $this->setupExternalResponse( $module, $params );
1021 $this->checkAsserts( $params );
1024 $module->profileIn();
1026 Hooks
::run( 'APIAfterExecute', array( &$module ) );
1027 $module->profileOut();
1029 $this->reportUnusedParams();
1031 if ( !$this->mInternalMode
) {
1032 //append Debug information
1033 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1035 // Print result data
1036 $this->printResult( false );
1041 * Log the preceding request
1042 * @param int $time Time in seconds
1044 protected function logRequest( $time ) {
1045 $request = $this->getRequest();
1046 $milliseconds = $time === null ?
'?' : round( $time * 1000 );
1048 ' ' . $request->getMethod() .
1049 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1050 ' ' . $request->getIP() .
1051 ' T=' . $milliseconds . 'ms';
1052 foreach ( $this->getParamsUsed() as $name ) {
1053 $value = $request->getVal( $name );
1054 if ( $value === null ) {
1057 $s .= ' ' . $name . '=';
1058 if ( strlen( $value ) > 256 ) {
1059 $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
1060 $s .= $encValue . '[...]';
1062 $s .= $this->encodeRequestLogValue( $value );
1066 wfDebugLog( 'api', $s, 'private' );
1070 * Encode a value in a format suitable for a space-separated log line.
1074 protected function encodeRequestLogValue( $s ) {
1077 $chars = ';@$!*(),/:';
1078 $numChars = strlen( $chars );
1079 for ( $i = 0; $i < $numChars; $i++
) {
1080 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1084 return strtr( rawurlencode( $s ), $table );
1088 * Get the request parameters used in the course of the preceding execute() request
1091 protected function getParamsUsed() {
1092 return array_keys( $this->mParamsUsed
);
1096 * Get a request value, and register the fact that it was used, for logging.
1097 * @param string $name
1098 * @param mixed $default
1101 public function getVal( $name, $default = null ) {
1102 $this->mParamsUsed
[$name] = true;
1104 $ret = $this->getRequest()->getVal( $name );
1105 if ( $ret === null ) {
1106 if ( $this->getRequest()->getArray( $name ) !== null ) {
1107 // See bug 10262 for why we don't just join( '|', ... ) the
1110 "Parameter '$name' uses unsupported PHP array syntax"
1119 * Get a boolean request value, and register the fact that the parameter
1120 * was used, for logging.
1121 * @param string $name
1124 public function getCheck( $name ) {
1125 return $this->getVal( $name, null ) !== null;
1129 * Get a request upload, and register the fact that it was used, for logging.
1132 * @param string $name Parameter name
1133 * @return WebRequestUpload
1135 public function getUpload( $name ) {
1136 $this->mParamsUsed
[$name] = true;
1138 return $this->getRequest()->getUpload( $name );
1142 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1143 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1145 protected function reportUnusedParams() {
1146 $paramsUsed = $this->getParamsUsed();
1147 $allParams = $this->getRequest()->getValueNames();
1149 if ( !$this->mInternalMode
) {
1150 // Printer has not yet executed; don't warn that its parameters are unused
1151 $printerParams = array_map(
1152 array( $this->mPrinter
, 'encodeParamName' ),
1153 array_keys( $this->mPrinter
->getFinalParams() ?
: array() )
1155 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1157 $unusedParams = array_diff( $allParams, $paramsUsed );
1160 if ( count( $unusedParams ) ) {
1161 $s = count( $unusedParams ) > 1 ?
's' : '';
1162 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1167 * Print results using the current printer
1169 * @param bool $isError
1171 protected function printResult( $isError ) {
1172 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1173 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1176 $this->getResult()->cleanUpUTF8();
1177 $printer = $this->mPrinter
;
1178 $printer->profileIn();
1180 $printer->initPrinter( false );
1182 $printer->execute();
1183 $printer->closePrinter();
1184 $printer->profileOut();
1190 public function isReadMode() {
1195 * See ApiBase for description.
1199 public function getAllowedParams() {
1202 ApiBase
::PARAM_DFLT
=> 'help',
1203 ApiBase
::PARAM_TYPE
=> 'submodule',
1206 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1207 ApiBase
::PARAM_TYPE
=> 'submodule',
1210 ApiBase
::PARAM_TYPE
=> 'integer'
1213 ApiBase
::PARAM_TYPE
=> 'integer',
1214 ApiBase
::PARAM_DFLT
=> 0
1217 ApiBase
::PARAM_TYPE
=> 'integer',
1218 ApiBase
::PARAM_DFLT
=> 0
1221 ApiBase
::PARAM_TYPE
=> array( 'user', 'bot' )
1223 'requestid' => null,
1224 'servedby' => false,
1225 'curtimestamp' => false,
1228 ApiBase
::PARAM_DFLT
=> 'user',
1233 /** @see ApiBase::getExamplesMessages() */
1234 protected function getExamplesMessages() {
1237 => 'apihelp-help-example-main',
1238 'action=help&recursivesubmodules=1'
1239 => 'apihelp-help-example-recursive',
1243 public function modifyHelp( array &$help, array $options ) {
1244 // Wish PHP had an "array_insert_before". Instead, we have to manually
1245 // reindex the array to get 'permissions' in the right place.
1248 foreach ( $oldHelp as $k => $v ) {
1249 if ( $k === 'submodules' ) {
1250 $help['permissions'] = '';
1254 $help['credits'] = '';
1256 // Fill 'permissions'
1257 $help['permissions'] .= Html
::openElement( 'div',
1258 array( 'class' => 'apihelp-block apihelp-permissions' ) );
1259 $m = $this->msg( 'api-help-permissions' );
1260 if ( !$m->isDisabled() ) {
1261 $help['permissions'] .= Html
::rawElement( 'div', array( 'class' => 'apihelp-block-head' ),
1262 $m->numParams( count( self
::$mRights ) )->parse()
1265 $help['permissions'] .= Html
::openElement( 'dl' );
1266 foreach ( self
::$mRights as $right => $rightMsg ) {
1267 $help['permissions'] .= Html
::element( 'dt', null, $right );
1269 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1270 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1272 $groups = array_map( function ( $group ) {
1273 return $group == '*' ?
'all' : $group;
1274 }, User
::getGroupsWithPermission( $right ) );
1276 $help['permissions'] .= Html
::rawElement( 'dd', null,
1277 $this->msg( 'api-help-permissions-granted-to' )
1278 ->numParams( count( $groups ) )
1279 ->params( $this->getLanguage()->commaList( $groups ) )
1283 $help['permissions'] .= Html
::closeElement( 'dl' );
1284 $help['permissions'] .= Html
::closeElement( 'div' );
1286 // Fill 'credits', if applicable
1287 if ( empty( $options['nolead'] ) ) {
1288 $help['credits'] .= Html
::element( 'h' . min( 6, $options['headerlevel'] +
1 ),
1289 array( 'id' => '+credits', 'class' => 'apihelp-header' ),
1290 $this->msg( 'api-credits-header' )->parse()
1292 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1296 private $mCanApiHighLimits = null;
1299 * Check whether the current user is allowed to use high limits
1302 public function canApiHighLimits() {
1303 if ( !isset( $this->mCanApiHighLimits
) ) {
1304 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1307 return $this->mCanApiHighLimits
;
1311 * Overrides to return this instance's module manager.
1312 * @return ApiModuleManager
1314 public function getModuleManager() {
1315 return $this->mModuleMgr
;
1319 * Fetches the user agent used for this request
1321 * The value will be the combination of the 'Api-User-Agent' header (if
1322 * any) and the standard User-Agent header (if any).
1326 public function getUserAgent() {
1328 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1329 $this->getRequest()->getHeader( 'User-agent' )
1333 /************************************************************************//**
1339 * Sets whether the pretty-printer should format *bold* and $italics$
1341 * @deprecated since 1.25
1344 public function setHelp( $help = true ) {
1345 wfDeprecated( __METHOD__
, '1.25' );
1346 $this->mPrinter
->setHelp( $help );
1350 * Override the parent to generate help messages for all available modules.
1352 * @deprecated since 1.25
1355 public function makeHelpMsg() {
1356 wfDeprecated( __METHOD__
, '1.25' );
1359 // Get help text from cache if present
1360 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1361 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) ) );
1363 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1364 if ( $cacheHelpTimeout > 0 ) {
1365 $cached = $wgMemc->get( $key );
1370 $retval = $this->reallyMakeHelpMsg();
1371 if ( $cacheHelpTimeout > 0 ) {
1372 $wgMemc->set( $key, $retval, $cacheHelpTimeout );
1379 * @deprecated since 1.25
1380 * @return mixed|string
1382 public function reallyMakeHelpMsg() {
1383 wfDeprecated( __METHOD__
, '1.25' );
1386 // Use parent to make default message for the main module
1387 $msg = parent
::makeHelpMsg();
1389 $astriks = str_repeat( '*** ', 14 );
1390 $msg .= "\n\n$astriks Modules $astriks\n\n";
1392 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1393 $module = $this->mModuleMgr
->getModule( $name );
1394 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1396 $msg2 = $module->makeHelpMsg();
1397 if ( $msg2 !== false ) {
1403 $msg .= "\n$astriks Permissions $astriks\n\n";
1404 foreach ( self
::$mRights as $right => $rightMsg ) {
1405 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1406 ->useDatabase( false )
1407 ->inLanguage( 'en' )
1409 $groups = User
::getGroupsWithPermission( $right );
1410 $msg .= "* " . $right . " *\n $rightsMsg" .
1411 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1414 $msg .= "\n$astriks Formats $astriks\n\n";
1415 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1416 $module = $this->mModuleMgr
->getModule( $name );
1417 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1418 $msg2 = $module->makeHelpMsg();
1419 if ( $msg2 !== false ) {
1425 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1426 $credits = str_replace( "\n", "\n ", $credits );
1427 $msg .= "\n*** Credits: ***\n $credits\n";
1433 * @deprecated since 1.25
1434 * @param ApiBase $module
1435 * @param string $paramName What type of request is this? e.g. action,
1436 * query, list, prop, meta, format
1439 public static function makeHelpMsgHeader( $module, $paramName ) {
1440 wfDeprecated( __METHOD__
, '1.25' );
1441 $modulePrefix = $module->getModulePrefix();
1442 if ( strval( $modulePrefix ) !== '' ) {
1443 $modulePrefix = "($modulePrefix) ";
1446 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1450 * Check whether the user wants us to show version information in the API help
1452 * @deprecated since 1.21, always returns false
1454 public function getShowVersions() {
1455 wfDeprecated( __METHOD__
, '1.21' );
1461 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1462 * classes who wish to add their own modules to their lexicon or override the
1463 * behavior of inherent ones.
1465 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1466 * @param string $name The identifier for this module.
1467 * @param ApiBase $class The class where this module is implemented.
1469 protected function addModule( $name, $class ) {
1470 $this->getModuleManager()->addModule( $name, 'action', $class );
1474 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1475 * classes who wish to add to or modify current formatters.
1477 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1478 * @param string $name The identifier for this format.
1479 * @param ApiFormatBase $class The class implementing this format.
1481 protected function addFormat( $name, $class ) {
1482 $this->getModuleManager()->addModule( $name, 'format', $class );
1486 * Get the array mapping module names to class names
1487 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1490 function getModules() {
1491 return $this->getModuleManager()->getNamesWithClasses( 'action' );
1495 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1498 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1501 public function getFormats() {
1502 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1510 * This exception will be thrown when dieUsage is called to stop module execution.
1514 class UsageException
extends MWException
{
1521 private $mExtraData;
1524 * @param string $message
1525 * @param string $codestr
1527 * @param array|null $extradata
1529 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1530 parent
::__construct( $message, $code );
1531 $this->mCodestr
= $codestr;
1532 $this->mExtraData
= $extradata;
1538 public function getCodeString() {
1539 return $this->mCodestr
;
1545 public function getMessageArray() {
1547 'code' => $this->mCodestr
,
1548 'info' => $this->getMessage()
1550 if ( is_array( $this->mExtraData
) ) {
1551 $result = array_merge( $result, $this->mExtraData
);
1560 public function __toString() {
1561 return "{$this->getCodeString()}: {$this->getMessage()}";
1566 * For really cool vim folding this needs to be at the end:
1567 * vim: foldmarker=@{,@} foldmethod=marker