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',
67 'checktoken' => 'ApiCheckToken',
70 'purge' => 'ApiPurge',
71 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
72 'rollback' => 'ApiRollback',
73 'delete' => 'ApiDelete',
74 'undelete' => 'ApiUndelete',
75 'protect' => 'ApiProtect',
76 'block' => 'ApiBlock',
77 'unblock' => 'ApiUnblock',
79 'edit' => 'ApiEditPage',
80 'upload' => 'ApiUpload',
81 'filerevert' => 'ApiFileRevert',
82 'emailuser' => 'ApiEmailUser',
83 'watch' => 'ApiWatch',
84 'patrol' => 'ApiPatrol',
85 'import' => 'ApiImport',
86 'clearhasmsg' => 'ApiClearHasMsg',
87 'userrights' => 'ApiUserrights',
88 'options' => 'ApiOptions',
89 'imagerotate' => 'ApiImageRotate',
90 'revisiondelete' => 'ApiRevisionDelete',
91 'managetags' => 'ApiManageTags',
96 * List of available formats: format name => format class
98 private static $Formats = array(
99 'json' => 'ApiFormatJson',
100 'jsonfm' => 'ApiFormatJson',
101 'php' => 'ApiFormatPhp',
102 'phpfm' => 'ApiFormatPhp',
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 'none' => 'ApiFormatNone',
115 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
117 * List of user roles that are specifically relevant to the API.
118 * array( 'right' => array ( 'msg' => 'Some message with a $1',
119 * 'params' => array ( $someVarToSubst ) ),
122 private static $mRights = array(
124 'msg' => 'right-writeapi',
127 'apihighlimits' => array(
128 'msg' => 'api-help-right-apihighlimits',
129 'params' => array( ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
)
132 // @codingStandardsIgnoreEnd
139 private $mModuleMgr, $mResult, $mErrorFormatter, $mContinuationManager;
141 private $mEnableWrite;
142 private $mInternalMode, $mSquidMaxage, $mModule;
144 private $mCacheMode = 'private';
145 private $mCacheControl = array();
146 private $mParamsUsed = array();
149 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
151 * @param IContextSource|WebRequest $context If this is an instance of
152 * FauxRequest, errors are thrown and no printing occurs
153 * @param bool $enableWrite Should be set to true if the api may modify data
155 public function __construct( $context = null, $enableWrite = false ) {
156 if ( $context === null ) {
157 $context = RequestContext
::getMain();
158 } elseif ( $context instanceof WebRequest
) {
161 $context = RequestContext
::getMain();
163 // We set a derivative context so we can change stuff later
164 $this->setContext( new DerivativeContext( $context ) );
166 if ( isset( $request ) ) {
167 $this->getContext()->setRequest( $request );
170 $this->mInternalMode
= ( $this->getRequest() instanceof FauxRequest
);
172 // Special handling for the main module: $parent === $this
173 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
175 if ( !$this->mInternalMode
) {
176 // Impose module restrictions.
177 // If the current user cannot read,
178 // Remove all modules other than login
181 if ( $this->lacksSameOriginSecurity() ) {
182 // If we're in a mode that breaks the same-origin policy, strip
183 // user credentials for security.
184 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
185 $wgUser = new User();
186 $this->getContext()->setUser( $wgUser );
190 $uselang = $this->getParameter( 'uselang' );
191 if ( $uselang === 'user' ) {
192 // Assume the parent context is going to return the user language
193 // for uselang=user (see T85635).
195 if ( $uselang === 'content' ) {
197 $uselang = $wgContLang->getCode();
199 $code = RequestContext
::sanitizeLangCode( $uselang );
200 $this->getContext()->setLanguage( $code );
201 if ( !$this->mInternalMode
) {
203 $wgLang = $this->getContext()->getLanguage();
204 RequestContext
::getMain()->setLanguage( $wgLang );
208 $config = $this->getConfig();
209 $this->mModuleMgr
= new ApiModuleManager( $this );
210 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
211 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
212 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
213 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
215 Hooks
::run( 'ApiMain::moduleManager', array( $this->mModuleMgr
) );
217 $this->mResult
= new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
218 $this->mErrorFormatter
= new ApiErrorFormatter_BackCompat( $this->mResult
);
219 $this->mResult
->setErrorFormatter( $this->mErrorFormatter
);
220 $this->mResult
->setMainForContinuation( $this );
221 $this->mContinuationManager
= null;
222 $this->mEnableWrite
= $enableWrite;
224 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
225 $this->mCommit
= false;
229 * Return true if the API was started by other PHP code using FauxRequest
232 public function isInternalMode() {
233 return $this->mInternalMode
;
237 * Get the ApiResult object associated with current request
241 public function getResult() {
242 return $this->mResult
;
246 * Get the ApiErrorFormatter object associated with current request
247 * @return ApiErrorFormatter
249 public function getErrorFormatter() {
250 return $this->mErrorFormatter
;
254 * Get the continuation manager
255 * @return ApiContinuationManager|null
257 public function getContinuationManager() {
258 return $this->mContinuationManager
;
262 * Set the continuation manager
263 * @param ApiContinuationManager|null
265 public function setContinuationManager( $manager ) {
266 if ( $manager !== null ) {
267 if ( !$manager instanceof ApiContinuationManager
) {
268 throw new InvalidArgumentException( __METHOD__
. ': Was passed ' .
269 is_object( $manager ) ?
get_class( $manager ) : gettype( $manager )
272 if ( $this->mContinuationManager
!== null ) {
273 throw new UnexpectedValueException(
274 __METHOD__
. ': tried to set manager from ' . $manager->getSource() .
275 ' when a manager is already set from ' . $this->mContinuationManager
->getSource()
279 $this->mContinuationManager
= $manager;
283 * Get the API module object. Only works after executeAction()
287 public function getModule() {
288 return $this->mModule
;
292 * Get the result formatter object. Only works after setupExecuteAction()
294 * @return ApiFormatBase
296 public function getPrinter() {
297 return $this->mPrinter
;
301 * Set how long the response should be cached.
305 public function setCacheMaxAge( $maxage ) {
306 $this->setCacheControl( array(
307 'max-age' => $maxage,
308 's-maxage' => $maxage
313 * Set the type of caching headers which will be sent.
315 * @param string $mode One of:
316 * - 'public': Cache this object in public caches, if the maxage or smaxage
317 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
318 * not provided by any of these means, the object will be private.
319 * - 'private': Cache this object only in private client-side caches.
320 * - 'anon-public-user-private': Make this object cacheable for logged-out
321 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
322 * set consistently for a given URL, it cannot be set differently depending on
323 * things like the contents of the database, or whether the user is logged in.
325 * If the wiki does not allow anonymous users to read it, the mode set here
326 * will be ignored, and private caching headers will always be sent. In other words,
327 * the "public" mode is equivalent to saying that the data sent is as public as a page
330 * For user-dependent data, the private mode should generally be used. The
331 * anon-public-user-private mode should only be used where there is a particularly
332 * good performance reason for caching the anonymous response, but where the
333 * response to logged-in users may differ, or may contain private data.
335 * If this function is never called, then the default will be the private mode.
337 public function setCacheMode( $mode ) {
338 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
339 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
341 // Ignore for forwards-compatibility
345 if ( !User
::isEveryoneAllowed( 'read' ) ) {
346 // Private wiki, only private headers
347 if ( $mode !== 'private' ) {
348 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
354 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
355 // User language is used for i18n, so we don't want to publicly
356 // cache. Anons are ok, because if they have non-default language
357 // then there's an appropriate Vary header set by whatever set
358 // their non-default language.
359 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
360 "'anon-public-user-private' due to uselang=user\n" );
361 $mode = 'anon-public-user-private';
364 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
365 $this->mCacheMode
= $mode;
369 * Set directives (key/value pairs) for the Cache-Control header.
370 * Boolean values will be formatted as such, by including or omitting
371 * without an equals sign.
373 * Cache control values set here will only be used if the cache mode is not
374 * private, see setCacheMode().
376 * @param array $directives
378 public function setCacheControl( $directives ) {
379 $this->mCacheControl
= $directives +
$this->mCacheControl
;
383 * Create an instance of an output formatter by its name
385 * @param string $format
387 * @return ApiFormatBase
389 public function createPrinterByName( $format ) {
390 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
391 if ( $printer === null ) {
392 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
399 * Execute api request. Any errors will be handled if the API was called by the remote client.
401 public function execute() {
402 if ( $this->mInternalMode
) {
403 $this->executeAction();
405 $this->executeActionWithErrorHandling();
410 * Execute an action, and in case of an error, erase whatever partial results
411 * have been accumulated, and replace it with an error message and a help screen.
413 protected function executeActionWithErrorHandling() {
414 // Verify the CORS header before executing the action
415 if ( !$this->handleCORS() ) {
416 // handleCORS() has sent a 403, abort
420 // Exit here if the request method was OPTIONS
421 // (assume there will be a followup GET or POST)
422 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
426 // In case an error occurs during data output,
427 // clear the output buffer and print just the error information
430 $t = microtime( true );
432 $this->executeAction();
433 } catch ( Exception
$e ) {
434 $this->handleException( $e );
437 // Log the request whether or not there was an error
438 $this->logRequest( microtime( true ) - $t );
440 // Send cache headers after any code which might generate an error, to
441 // avoid sending public cache headers for errors.
442 $this->sendCacheHeaders();
448 * Handle an exception as an API response
451 * @param Exception $e
453 protected function handleException( Exception
$e ) {
454 // Bug 63145: Rollback any open database transactions
455 if ( !( $e instanceof UsageException
) ) {
456 // UsageExceptions are intentional, so don't rollback if that's the case
458 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
459 } catch ( DBError
$e2 ) {
460 // Rollback threw an exception too. Log it, but don't interrupt
461 // our regularly scheduled exception handling.
462 MWExceptionHandler
::logException( $e2 );
466 // Allow extra cleanup and logging
467 Hooks
::run( 'ApiMain::onException', array( $this, $e ) );
470 if ( !( $e instanceof UsageException
) ) {
471 MWExceptionHandler
::logException( $e );
474 // Handle any kind of exception by outputting properly formatted error message.
475 // If this fails, an unhandled exception should be thrown so that global error
476 // handler will process and log it.
478 $errCode = $this->substituteResultWithError( $e );
480 // Error results should not be cached
481 $this->setCacheMode( 'private' );
483 $response = $this->getRequest()->response();
484 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
485 if ( $e->getCode() === 0 ) {
486 $response->header( $headerStr );
488 $response->header( $headerStr, true, $e->getCode() );
491 // Reset and print just the error message
494 // Printer may not be initialized if the extractRequestParams() fails for the main module
495 $this->createErrorPrinter();
498 $this->printResult( true );
499 } catch ( UsageException
$ex ) {
500 // The error printer itself is failing. Try suppressing its request
501 // parameters and redo.
503 'Error printer failed (will retry without params): ' . $ex->getMessage()
505 $this->mPrinter
= null;
506 $this->createErrorPrinter();
507 $this->mPrinter
->forceDefaultParams();
508 $this->printResult( true );
513 * Handle an exception from the ApiBeforeMain hook.
515 * This tries to print the exception as an API response, to be more
516 * friendly to clients. If it fails, it will rethrow the exception.
519 * @param Exception $e
522 public static function handleApiBeforeMainException( Exception
$e ) {
526 $main = new self( RequestContext
::getMain(), false );
527 $main->handleException( $e );
528 } catch ( Exception
$e2 ) {
529 // Nope, even that didn't work. Punt.
533 // Log the request and reset cache headers
534 $main->logRequest( 0 );
535 $main->sendCacheHeaders();
541 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
543 * If no origin parameter is present, nothing happens.
544 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
545 * is set and false is returned.
546 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
547 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
549 * http://www.w3.org/TR/cors/#resource-requests
550 * http://www.w3.org/TR/cors/#resource-preflight-requests
552 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
554 protected function handleCORS() {
555 $originParam = $this->getParameter( 'origin' ); // defaults to null
556 if ( $originParam === null ) {
557 // No origin parameter, nothing to do
561 $request = $this->getRequest();
562 $response = $request->response();
564 // Origin: header is a space-separated list of origins, check all of them
565 $originHeader = $request->getHeader( 'Origin' );
566 if ( $originHeader === false ) {
569 $originHeader = trim( $originHeader );
570 $origins = preg_split( '/\s+/', $originHeader );
573 if ( !in_array( $originParam, $origins ) ) {
574 // origin parameter set but incorrect
575 // Send a 403 response
576 $response->statusHeader( 403 );
577 $response->header( 'Cache-Control: no-cache' );
578 echo "'origin' parameter does not match Origin header\n";
583 $config = $this->getConfig();
584 $matchOrigin = count( $origins ) === 1 && self
::matchOrigin(
586 $config->get( 'CrossSiteAJAXdomains' ),
587 $config->get( 'CrossSiteAJAXdomainExceptions' )
590 if ( $matchOrigin ) {
591 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
592 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
594 // This is a CORS preflight request
595 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
596 // If method is not a case-sensitive match, do not set any additional headers and terminate.
599 // We allow the actual request to send the following headers
600 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
601 if ( $requestedHeaders !== false ) {
602 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
605 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
608 // We only allow the actual request to be GET or POST
609 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
612 $response->header( "Access-Control-Allow-Origin: $originHeader" );
613 $response->header( 'Access-Control-Allow-Credentials: true' );
614 $response->header( "Timing-Allow-Origin: $originHeader" ); # http://www.w3.org/TR/resource-timing/#timing-allow-origin
617 $response->header( 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag' );
621 $this->getOutput()->addVaryHeader( 'Origin' );
626 * Attempt to match an Origin header against a set of rules and a set of exceptions
627 * @param string $value Origin header
628 * @param array $rules Set of wildcard rules
629 * @param array $exceptions Set of wildcard rules
630 * @return bool True if $value matches a rule in $rules and doesn't match
631 * any rules in $exceptions, false otherwise
633 protected static function matchOrigin( $value, $rules, $exceptions ) {
634 foreach ( $rules as $rule ) {
635 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
636 // Rule matches, check exceptions
637 foreach ( $exceptions as $exc ) {
638 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
651 * Attempt to validate the value of Access-Control-Request-Headers against a list
652 * of headers that we allow the follow up request to send.
654 * @param string $requestedHeaders Comma seperated list of HTTP headers
655 * @return bool True if all requested headers are in the list of allowed headers
657 protected static function matchRequestedHeaders( $requestedHeaders ) {
658 if ( trim( $requestedHeaders ) === '' ) {
661 $requestedHeaders = explode( ',', $requestedHeaders );
662 $allowedAuthorHeaders = array_flip( array(
663 /* simple headers (see spec) */
668 /* non-authorable headers in XHR, which are however requested by some UAs */
672 /* MediaWiki whitelist */
675 foreach ( $requestedHeaders as $rHeader ) {
676 $rHeader = strtolower( trim( $rHeader ) );
677 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
678 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
686 * Helper function to convert wildcard string into a regex
690 * @param string $wildcard String with wildcards
691 * @return string Regular expression
693 protected static function wildcardToRegex( $wildcard ) {
694 $wildcard = preg_quote( $wildcard, '/' );
695 $wildcard = str_replace(
701 return "/^https?:\/\/$wildcard$/";
704 protected function sendCacheHeaders() {
705 $response = $this->getRequest()->response();
706 $out = $this->getOutput();
708 $config = $this->getConfig();
710 if ( $config->get( 'VaryOnXFP' ) ) {
711 $out->addVaryHeader( 'X-Forwarded-Proto' );
714 // The logic should be:
715 // $this->mCacheControl['max-age'] is set?
716 // Use it, the module knows better than our guess.
717 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
718 // Use 0 because we can guess caching is probably the wrong thing to do.
719 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
721 if ( isset( $this->mCacheControl
['max-age'] ) ) {
722 $maxage = $this->mCacheControl
['max-age'];
723 } elseif ( ( $this->mModule
&& !$this->mModule
->isWriteMode() ) ||
724 $this->mCacheMode
!== 'private'
726 $maxage = $this->getParameter( 'maxage' );
728 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
730 if ( $this->mCacheMode
== 'private' ) {
731 $response->header( "Cache-Control: $privateCache" );
735 $useXVO = $config->get( 'UseXVO' );
736 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
737 $out->addVaryHeader( 'Cookie' );
738 $response->header( $out->getVaryHeader() );
740 $response->header( $out->getXVO() );
741 if ( $out->haveCacheVaryCookies() ) {
742 // Logged in, mark this request private
743 $response->header( "Cache-Control: $privateCache" );
746 // Logged out, send normal public headers below
747 } elseif ( session_id() != '' ) {
748 // Logged in or otherwise has session (e.g. anonymous users who have edited)
749 // Mark request private
750 $response->header( "Cache-Control: $privateCache" );
753 } // else no XVO and anonymous, send public headers below
756 // Send public headers
757 $response->header( $out->getVaryHeader() );
759 $response->header( $out->getXVO() );
762 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
763 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
764 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
766 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
767 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
770 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
771 // Public cache not requested
772 // Sending a Vary header in this case is harmless, and protects us
773 // against conditional calls of setCacheMaxAge().
774 $response->header( "Cache-Control: $privateCache" );
779 $this->mCacheControl
['public'] = true;
781 // Send an Expires header
782 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
783 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
784 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
786 // Construct the Cache-Control header
789 foreach ( $this->mCacheControl
as $name => $value ) {
790 if ( is_bool( $value ) ) {
792 $ccHeader .= $separator . $name;
796 $ccHeader .= $separator . "$name=$value";
801 $response->header( "Cache-Control: $ccHeader" );
805 * Create the printer for error output
807 private function createErrorPrinter() {
808 if ( !isset( $this->mPrinter
) ) {
809 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
810 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
811 $value = self
::API_DEFAULT_FORMAT
;
813 $this->mPrinter
= $this->createPrinterByName( $value );
816 // Printer may not be able to handle errors. This is particularly
817 // likely if the module returns something for getCustomPrinter().
818 if ( !$this->mPrinter
->canPrintErrors() ) {
819 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
824 * Replace the result data with the information about an exception.
825 * Returns the error code
826 * @param Exception $e
829 protected function substituteResultWithError( $e ) {
830 $result = $this->getResult();
831 $config = $this->getConfig();
833 if ( $e instanceof UsageException
) {
834 // User entered incorrect parameters - generate error response
835 $errMessage = $e->getMessageArray();
836 $link = wfExpandUrl( wfScript( 'api' ) );
837 ApiResult
::setContentValue( $errMessage, 'docref', "See $link for API usage" );
839 // Something is seriously wrong
840 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
841 $info = 'Database query error';
843 $info = "Exception Caught: {$e->getMessage()}";
847 'code' => 'internal_api_error_' . get_class( $e ),
848 'info' => '[' . MWExceptionHandler
::getLogId( $e ) . '] ' . $info,
850 if ( $config->get( 'ShowExceptionDetails' ) ) {
851 ApiResult
::setContentValue(
854 MWExceptionHandler
::getRedactedTraceAsString( $e )
859 // Remember all the warnings to re-add them later
860 $warnings = $result->getResultData( array( 'warnings' ) );
864 $requestid = $this->getParameter( 'requestid' );
865 if ( !is_null( $requestid ) ) {
866 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
868 if ( $config->get( 'ShowHostnames' ) ) {
869 // servedby is especially useful when debugging errors
870 $result->addValue( null, 'servedby', wfHostName(), ApiResult
::NO_SIZE_CHECK
);
872 if ( $warnings !== null ) {
873 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
876 $result->addValue( null, 'error', $errMessage, ApiResult
::NO_SIZE_CHECK
);
878 return $errMessage['code'];
882 * Set up for the execution.
885 protected function setupExecuteAction() {
886 // First add the id to the top element
887 $result = $this->getResult();
888 $requestid = $this->getParameter( 'requestid' );
889 if ( !is_null( $requestid ) ) {
890 $result->addValue( null, 'requestid', $requestid );
893 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
894 $servedby = $this->getParameter( 'servedby' );
896 $result->addValue( null, 'servedby', wfHostName() );
900 if ( $this->getParameter( 'curtimestamp' ) ) {
901 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
902 ApiResult
::NO_SIZE_CHECK
);
905 $params = $this->extractRequestParams();
907 $this->mAction
= $params['action'];
909 if ( !is_string( $this->mAction
) ) {
910 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
917 * Set up the module for response
918 * @return ApiBase The module that will handle this action
919 * @throws MWException
920 * @throws UsageException
922 protected function setupModule() {
923 // Instantiate the module requested by the user
924 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
925 if ( $module === null ) {
926 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
928 $moduleParams = $module->extractRequestParams();
930 // Check token, if necessary
931 if ( $module->needsToken() === true ) {
932 throw new MWException(
933 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
934 "See documentation for ApiBase::needsToken for details."
937 if ( $module->needsToken() ) {
938 if ( !$module->mustBePosted() ) {
939 throw new MWException(
940 "Module '{$module->getModuleName()}' must require POST to use tokens."
944 if ( !isset( $moduleParams['token'] ) ) {
945 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
948 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
950 $module->encodeParamName( 'token' ),
951 $this->getRequest()->getQueryValues()
955 "The '{$module->encodeParamName( 'token' )}' parameter was found in the query string, but must be in the POST body",
960 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
961 $this->dieUsageMsg( 'sessionfailure' );
969 * Check the max lag if necessary
970 * @param ApiBase $module Api module being used
971 * @param array $params Array an array containing the request parameters.
972 * @return bool True on success, false should exit immediately
974 protected function checkMaxLag( $module, $params ) {
975 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
977 $maxLag = $params['maxlag'];
978 list( $host, $lag ) = wfGetLB()->getMaxLag();
979 if ( $lag > $maxLag ) {
980 $response = $this->getRequest()->response();
982 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
983 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
985 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
986 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
989 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
997 * Check for sufficient permissions to execute
998 * @param ApiBase $module An Api module
1000 protected function checkExecutePermissions( $module ) {
1001 $user = $this->getUser();
1002 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
1003 !$user->isAllowed( 'read' )
1005 $this->dieUsageMsg( 'readrequired' );
1007 if ( $module->isWriteMode() ) {
1008 if ( !$this->mEnableWrite
) {
1009 $this->dieUsageMsg( 'writedisabled' );
1011 if ( !$user->isAllowed( 'writeapi' ) ) {
1012 $this->dieUsageMsg( 'writerequired' );
1014 if ( wfReadOnly() ) {
1015 $this->dieReadOnly();
1019 // Allow extensions to stop execution for arbitrary reasons.
1021 if ( !Hooks
::run( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
1022 $this->dieUsageMsg( $message );
1027 * Check asserts of the user's rights
1028 * @param array $params
1030 protected function checkAsserts( $params ) {
1031 if ( isset( $params['assert'] ) ) {
1032 $user = $this->getUser();
1033 switch ( $params['assert'] ) {
1035 if ( $user->isAnon() ) {
1036 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
1040 if ( !$user->isAllowed( 'bot' ) ) {
1041 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1049 * Check POST for external response and setup result printer
1050 * @param ApiBase $module An Api module
1051 * @param array $params An array with the request parameters
1053 protected function setupExternalResponse( $module, $params ) {
1054 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
1055 // Module requires POST. GET request might still be allowed
1056 // if $wgDebugApi is true, otherwise fail.
1057 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction
) );
1060 // See if custom printer is used
1061 $this->mPrinter
= $module->getCustomPrinter();
1062 if ( is_null( $this->mPrinter
) ) {
1063 // Create an appropriate printer
1064 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1067 if ( $this->mPrinter
->getNeedsRawData() ) {
1068 $this->getResult()->setRawMode();
1073 * Execute the actual module, without any error handling
1075 protected function executeAction() {
1076 $params = $this->setupExecuteAction();
1077 $module = $this->setupModule();
1078 $this->mModule
= $module;
1080 $this->checkExecutePermissions( $module );
1082 if ( !$this->checkMaxLag( $module, $params ) ) {
1086 if ( !$this->mInternalMode
) {
1087 $this->setupExternalResponse( $module, $params );
1090 $this->checkAsserts( $params );
1094 Hooks
::run( 'APIAfterExecute', array( &$module ) );
1096 $this->reportUnusedParams();
1098 if ( !$this->mInternalMode
) {
1099 //append Debug information
1100 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1102 // Print result data
1103 $this->printResult( false );
1108 * Log the preceding request
1109 * @param int $time Time in seconds
1111 protected function logRequest( $time ) {
1112 $request = $this->getRequest();
1113 $milliseconds = $time === null ?
'?' : round( $time * 1000 );
1115 ' ' . $request->getMethod() .
1116 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1117 ' ' . $request->getIP() .
1118 ' T=' . $milliseconds . 'ms';
1119 foreach ( $this->getParamsUsed() as $name ) {
1120 $value = $request->getVal( $name );
1121 if ( $value === null ) {
1124 $s .= ' ' . $name . '=';
1125 if ( strlen( $value ) > 256 ) {
1126 $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
1127 $s .= $encValue . '[...]';
1129 $s .= $this->encodeRequestLogValue( $value );
1133 wfDebugLog( 'api', $s, 'private' );
1137 * Encode a value in a format suitable for a space-separated log line.
1141 protected function encodeRequestLogValue( $s ) {
1144 $chars = ';@$!*(),/:';
1145 $numChars = strlen( $chars );
1146 for ( $i = 0; $i < $numChars; $i++
) {
1147 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1151 return strtr( rawurlencode( $s ), $table );
1155 * Get the request parameters used in the course of the preceding execute() request
1158 protected function getParamsUsed() {
1159 return array_keys( $this->mParamsUsed
);
1163 * Get a request value, and register the fact that it was used, for logging.
1164 * @param string $name
1165 * @param mixed $default
1168 public function getVal( $name, $default = null ) {
1169 $this->mParamsUsed
[$name] = true;
1171 $ret = $this->getRequest()->getVal( $name );
1172 if ( $ret === null ) {
1173 if ( $this->getRequest()->getArray( $name ) !== null ) {
1174 // See bug 10262 for why we don't just join( '|', ... ) the
1177 "Parameter '$name' uses unsupported PHP array syntax"
1186 * Get a boolean request value, and register the fact that the parameter
1187 * was used, for logging.
1188 * @param string $name
1191 public function getCheck( $name ) {
1192 return $this->getVal( $name, null ) !== null;
1196 * Get a request upload, and register the fact that it was used, for logging.
1199 * @param string $name Parameter name
1200 * @return WebRequestUpload
1202 public function getUpload( $name ) {
1203 $this->mParamsUsed
[$name] = true;
1205 return $this->getRequest()->getUpload( $name );
1209 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1210 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1212 protected function reportUnusedParams() {
1213 $paramsUsed = $this->getParamsUsed();
1214 $allParams = $this->getRequest()->getValueNames();
1216 if ( !$this->mInternalMode
) {
1217 // Printer has not yet executed; don't warn that its parameters are unused
1218 $printerParams = array_map(
1219 array( $this->mPrinter
, 'encodeParamName' ),
1220 array_keys( $this->mPrinter
->getFinalParams() ?
: array() )
1222 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1224 $unusedParams = array_diff( $allParams, $paramsUsed );
1227 if ( count( $unusedParams ) ) {
1228 $s = count( $unusedParams ) > 1 ?
's' : '';
1229 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1234 * Print results using the current printer
1236 * @param bool $isError
1238 protected function printResult( $isError ) {
1239 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1240 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1243 $printer = $this->mPrinter
;
1244 $printer->initPrinter( false );
1245 $printer->execute();
1246 $printer->closePrinter();
1252 public function isReadMode() {
1257 * See ApiBase for description.
1261 public function getAllowedParams() {
1264 ApiBase
::PARAM_DFLT
=> 'help',
1265 ApiBase
::PARAM_TYPE
=> 'submodule',
1268 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1269 ApiBase
::PARAM_TYPE
=> 'submodule',
1272 ApiBase
::PARAM_TYPE
=> 'integer'
1275 ApiBase
::PARAM_TYPE
=> 'integer',
1276 ApiBase
::PARAM_DFLT
=> 0
1279 ApiBase
::PARAM_TYPE
=> 'integer',
1280 ApiBase
::PARAM_DFLT
=> 0
1283 ApiBase
::PARAM_TYPE
=> array( 'user', 'bot' )
1285 'requestid' => null,
1286 'servedby' => false,
1287 'curtimestamp' => false,
1290 ApiBase
::PARAM_DFLT
=> 'user',
1295 /** @see ApiBase::getExamplesMessages() */
1296 protected function getExamplesMessages() {
1299 => 'apihelp-help-example-main',
1300 'action=help&recursivesubmodules=1'
1301 => 'apihelp-help-example-recursive',
1305 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1306 // Wish PHP had an "array_insert_before". Instead, we have to manually
1307 // reindex the array to get 'permissions' in the right place.
1310 foreach ( $oldHelp as $k => $v ) {
1311 if ( $k === 'submodules' ) {
1312 $help['permissions'] = '';
1316 $help['datatypes'] = '';
1317 $help['credits'] = '';
1319 // Fill 'permissions'
1320 $help['permissions'] .= Html
::openElement( 'div',
1321 array( 'class' => 'apihelp-block apihelp-permissions' ) );
1322 $m = $this->msg( 'api-help-permissions' );
1323 if ( !$m->isDisabled() ) {
1324 $help['permissions'] .= Html
::rawElement( 'div', array( 'class' => 'apihelp-block-head' ),
1325 $m->numParams( count( self
::$mRights ) )->parse()
1328 $help['permissions'] .= Html
::openElement( 'dl' );
1329 foreach ( self
::$mRights as $right => $rightMsg ) {
1330 $help['permissions'] .= Html
::element( 'dt', null, $right );
1332 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1333 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1335 $groups = array_map( function ( $group ) {
1336 return $group == '*' ?
'all' : $group;
1337 }, User
::getGroupsWithPermission( $right ) );
1339 $help['permissions'] .= Html
::rawElement( 'dd', null,
1340 $this->msg( 'api-help-permissions-granted-to' )
1341 ->numParams( count( $groups ) )
1342 ->params( $this->getLanguage()->commaList( $groups ) )
1346 $help['permissions'] .= Html
::closeElement( 'dl' );
1347 $help['permissions'] .= Html
::closeElement( 'div' );
1349 // Fill 'datatypes' and 'credits', if applicable
1350 if ( empty( $options['nolead'] ) ) {
1351 $level = $options['headerlevel'];
1352 $tocnumber = &$options['tocnumber'];
1354 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1355 $help['datatypes'] .= Html
::rawelement( 'h' . min( 6, $level ),
1356 array( 'id' => 'main/datatypes', 'class' => 'apihelp-header' ),
1357 Html
::element( 'span', array( 'id' => Sanitizer
::escapeId( 'main/datatypes' ) ) ) .
1360 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1361 if ( !isset( $tocData['main/datatypes'] ) ) {
1362 $tocnumber[$level]++
;
1363 $tocData['main/datatypes'] = array(
1364 'toclevel' => count( $tocnumber ),
1366 'anchor' => 'main/datatypes',
1368 'number' => join( '.', $tocnumber ),
1373 $header = $this->msg( 'api-credits-header' )->parse();
1374 $help['credits'] .= Html
::rawelement( 'h' . min( 6, $level ),
1375 array( 'id' => 'main/credits', 'class' => 'apihelp-header' ),
1376 Html
::element( 'span', array( 'id' => Sanitizer
::escapeId( 'main/credits' ) ) ) .
1379 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1380 if ( !isset( $tocData['main/credits'] ) ) {
1381 $tocnumber[$level]++
;
1382 $tocData['main/credits'] = array(
1383 'toclevel' => count( $tocnumber ),
1385 'anchor' => 'main/credits',
1387 'number' => join( '.', $tocnumber ),
1394 private $mCanApiHighLimits = null;
1397 * Check whether the current user is allowed to use high limits
1400 public function canApiHighLimits() {
1401 if ( !isset( $this->mCanApiHighLimits
) ) {
1402 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1405 return $this->mCanApiHighLimits
;
1409 * Overrides to return this instance's module manager.
1410 * @return ApiModuleManager
1412 public function getModuleManager() {
1413 return $this->mModuleMgr
;
1417 * Fetches the user agent used for this request
1419 * The value will be the combination of the 'Api-User-Agent' header (if
1420 * any) and the standard User-Agent header (if any).
1424 public function getUserAgent() {
1426 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1427 $this->getRequest()->getHeader( 'User-agent' )
1431 /************************************************************************//**
1437 * Sets whether the pretty-printer should format *bold* and $italics$
1439 * @deprecated since 1.25
1442 public function setHelp( $help = true ) {
1443 wfDeprecated( __METHOD__
, '1.25' );
1444 $this->mPrinter
->setHelp( $help );
1448 * Override the parent to generate help messages for all available modules.
1450 * @deprecated since 1.25
1453 public function makeHelpMsg() {
1454 wfDeprecated( __METHOD__
, '1.25' );
1457 // Get help text from cache if present
1458 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1459 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) ) );
1461 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1462 if ( $cacheHelpTimeout > 0 ) {
1463 $cached = $wgMemc->get( $key );
1468 $retval = $this->reallyMakeHelpMsg();
1469 if ( $cacheHelpTimeout > 0 ) {
1470 $wgMemc->set( $key, $retval, $cacheHelpTimeout );
1477 * @deprecated since 1.25
1478 * @return mixed|string
1480 public function reallyMakeHelpMsg() {
1481 wfDeprecated( __METHOD__
, '1.25' );
1484 // Use parent to make default message for the main module
1485 $msg = parent
::makeHelpMsg();
1487 $astriks = str_repeat( '*** ', 14 );
1488 $msg .= "\n\n$astriks Modules $astriks\n\n";
1490 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1491 $module = $this->mModuleMgr
->getModule( $name );
1492 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1494 $msg2 = $module->makeHelpMsg();
1495 if ( $msg2 !== false ) {
1501 $msg .= "\n$astriks Permissions $astriks\n\n";
1502 foreach ( self
::$mRights as $right => $rightMsg ) {
1503 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1504 ->useDatabase( false )
1505 ->inLanguage( 'en' )
1507 $groups = User
::getGroupsWithPermission( $right );
1508 $msg .= "* " . $right . " *\n $rightsMsg" .
1509 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1512 $msg .= "\n$astriks Formats $astriks\n\n";
1513 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1514 $module = $this->mModuleMgr
->getModule( $name );
1515 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1516 $msg2 = $module->makeHelpMsg();
1517 if ( $msg2 !== false ) {
1523 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1524 $credits = str_replace( "\n", "\n ", $credits );
1525 $msg .= "\n*** Credits: ***\n $credits\n";
1531 * @deprecated since 1.25
1532 * @param ApiBase $module
1533 * @param string $paramName What type of request is this? e.g. action,
1534 * query, list, prop, meta, format
1537 public static function makeHelpMsgHeader( $module, $paramName ) {
1538 wfDeprecated( __METHOD__
, '1.25' );
1539 $modulePrefix = $module->getModulePrefix();
1540 if ( strval( $modulePrefix ) !== '' ) {
1541 $modulePrefix = "($modulePrefix) ";
1544 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1548 * Check whether the user wants us to show version information in the API help
1550 * @deprecated since 1.21, always returns false
1552 public function getShowVersions() {
1553 wfDeprecated( __METHOD__
, '1.21' );
1559 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1560 * classes who wish to add their own modules to their lexicon or override the
1561 * behavior of inherent ones.
1563 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1564 * @param string $name The identifier for this module.
1565 * @param ApiBase $class The class where this module is implemented.
1567 protected function addModule( $name, $class ) {
1568 $this->getModuleManager()->addModule( $name, 'action', $class );
1572 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1573 * classes who wish to add to or modify current formatters.
1575 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1576 * @param string $name The identifier for this format.
1577 * @param ApiFormatBase $class The class implementing this format.
1579 protected function addFormat( $name, $class ) {
1580 $this->getModuleManager()->addModule( $name, 'format', $class );
1584 * Get the array mapping module names to class names
1585 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1588 function getModules() {
1589 return $this->getModuleManager()->getNamesWithClasses( 'action' );
1593 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1596 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1599 public function getFormats() {
1600 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1608 * This exception will be thrown when dieUsage is called to stop module execution.
1612 class UsageException
extends MWException
{
1619 private $mExtraData;
1622 * @param string $message
1623 * @param string $codestr
1625 * @param array|null $extradata
1627 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1628 parent
::__construct( $message, $code );
1629 $this->mCodestr
= $codestr;
1630 $this->mExtraData
= $extradata;
1636 public function getCodeString() {
1637 return $this->mCodestr
;
1643 public function getMessageArray() {
1645 'code' => $this->mCodestr
,
1646 'info' => $this->getMessage()
1648 if ( is_array( $this->mExtraData
) ) {
1649 $result = array_merge( $result, $this->mExtraData
);
1658 public function __toString() {
1659 return "{$this->getCodeString()}: {$this->getMessage()}";
1664 * For really cool vim folding this needs to be at the end:
1665 * vim: foldmarker=@{,@} foldmethod=marker