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 'wddx' => 'ApiFormatWddx',
104 'wddxfm' => 'ApiFormatWddx',
105 'xml' => 'ApiFormatXml',
106 'xmlfm' => 'ApiFormatXml',
107 'yaml' => 'ApiFormatYaml',
108 'yamlfm' => 'ApiFormatYaml',
109 'rawfm' => 'ApiFormatJson',
110 'txt' => 'ApiFormatTxt',
111 'txtfm' => 'ApiFormatTxt',
112 'dbg' => 'ApiFormatDbg',
113 'dbgfm' => 'ApiFormatDbg',
114 'dump' => 'ApiFormatDump',
115 'dumpfm' => 'ApiFormatDump',
116 'none' => 'ApiFormatNone',
119 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
121 * List of user roles that are specifically relevant to the API.
122 * array( 'right' => array ( 'msg' => 'Some message with a $1',
123 * 'params' => array ( $someVarToSubst ) ),
126 private static $mRights = array(
128 'msg' => 'right-writeapi',
131 'apihighlimits' => array(
132 'msg' => 'api-help-right-apihighlimits',
133 'params' => array( ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
)
136 // @codingStandardsIgnoreEnd
143 private $mModuleMgr, $mResult, $mErrorFormatter, $mContinuationManager;
145 private $mEnableWrite;
146 private $mInternalMode, $mSquidMaxage, $mModule;
148 private $mCacheMode = 'private';
149 private $mCacheControl = array();
150 private $mParamsUsed = array();
153 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
155 * @param IContextSource|WebRequest $context If this is an instance of
156 * FauxRequest, errors are thrown and no printing occurs
157 * @param bool $enableWrite Should be set to true if the api may modify data
159 public function __construct( $context = null, $enableWrite = false ) {
160 if ( $context === null ) {
161 $context = RequestContext
::getMain();
162 } elseif ( $context instanceof WebRequest
) {
165 $context = RequestContext
::getMain();
167 // We set a derivative context so we can change stuff later
168 $this->setContext( new DerivativeContext( $context ) );
170 if ( isset( $request ) ) {
171 $this->getContext()->setRequest( $request );
174 $this->mInternalMode
= ( $this->getRequest() instanceof FauxRequest
);
176 // Special handling for the main module: $parent === $this
177 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
179 if ( !$this->mInternalMode
) {
180 // Impose module restrictions.
181 // If the current user cannot read,
182 // Remove all modules other than login
185 if ( $this->lacksSameOriginSecurity() ) {
186 // If we're in a mode that breaks the same-origin policy, strip
187 // user credentials for security.
188 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
189 $wgUser = new User();
190 $this->getContext()->setUser( $wgUser );
194 $uselang = $this->getParameter( 'uselang' );
195 if ( $uselang === 'user' ) {
196 // Assume the parent context is going to return the user language
197 // for uselang=user (see T85635).
199 if ( $uselang === 'content' ) {
201 $uselang = $wgContLang->getCode();
203 $code = RequestContext
::sanitizeLangCode( $uselang );
204 $this->getContext()->setLanguage( $code );
205 if ( !$this->mInternalMode
) {
207 $wgLang = $this->getContext()->getLanguage();
208 RequestContext
::getMain()->setLanguage( $wgLang );
212 $config = $this->getConfig();
213 $this->mModuleMgr
= new ApiModuleManager( $this );
214 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
215 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
216 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
217 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
219 Hooks
::run( 'ApiMain::moduleManager', array( $this->mModuleMgr
) );
221 $this->mResult
= new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
222 $this->mErrorFormatter
= new ApiErrorFormatter_BackCompat( $this->mResult
);
223 $this->mResult
->setErrorFormatter( $this->mErrorFormatter
);
224 $this->mResult
->setMainForContinuation( $this );
225 $this->mContinuationManager
= null;
226 $this->mEnableWrite
= $enableWrite;
228 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
229 $this->mCommit
= false;
233 * Return true if the API was started by other PHP code using FauxRequest
236 public function isInternalMode() {
237 return $this->mInternalMode
;
241 * Get the ApiResult object associated with current request
245 public function getResult() {
246 return $this->mResult
;
250 * Get the ApiErrorFormatter object associated with current request
251 * @return ApiErrorFormatter
253 public function getErrorFormatter() {
254 return $this->mErrorFormatter
;
258 * Get the continuation manager
259 * @return ApiContinuationManager|null
261 public function getContinuationManager() {
262 return $this->mContinuationManager
;
266 * Set the continuation manager
267 * @param ApiContinuationManager|null
269 public function setContinuationManager( $manager ) {
270 if ( $manager !== null ) {
271 if ( !$manager instanceof ApiContinuationManager
) {
272 throw new InvalidArgumentException( __METHOD__
. ': Was passed ' .
273 is_object( $manager ) ?
get_class( $manager ) : gettype( $manager )
276 if ( $this->mContinuationManager
!== null ) {
277 throw new UnexpectedValueException(
278 __METHOD__
. ': tried to set manager from ' . $manager->getSource() .
279 ' when a manager is already set from ' . $this->mContinuationManager
->getSource()
283 $this->mContinuationManager
= $manager;
287 * Get the API module object. Only works after executeAction()
291 public function getModule() {
292 return $this->mModule
;
296 * Get the result formatter object. Only works after setupExecuteAction()
298 * @return ApiFormatBase
300 public function getPrinter() {
301 return $this->mPrinter
;
305 * Set how long the response should be cached.
309 public function setCacheMaxAge( $maxage ) {
310 $this->setCacheControl( array(
311 'max-age' => $maxage,
312 's-maxage' => $maxage
317 * Set the type of caching headers which will be sent.
319 * @param string $mode One of:
320 * - 'public': Cache this object in public caches, if the maxage or smaxage
321 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
322 * not provided by any of these means, the object will be private.
323 * - 'private': Cache this object only in private client-side caches.
324 * - 'anon-public-user-private': Make this object cacheable for logged-out
325 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
326 * set consistently for a given URL, it cannot be set differently depending on
327 * things like the contents of the database, or whether the user is logged in.
329 * If the wiki does not allow anonymous users to read it, the mode set here
330 * will be ignored, and private caching headers will always be sent. In other words,
331 * the "public" mode is equivalent to saying that the data sent is as public as a page
334 * For user-dependent data, the private mode should generally be used. The
335 * anon-public-user-private mode should only be used where there is a particularly
336 * good performance reason for caching the anonymous response, but where the
337 * response to logged-in users may differ, or may contain private data.
339 * If this function is never called, then the default will be the private mode.
341 public function setCacheMode( $mode ) {
342 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
343 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
345 // Ignore for forwards-compatibility
349 if ( !User
::isEveryoneAllowed( 'read' ) ) {
350 // Private wiki, only private headers
351 if ( $mode !== 'private' ) {
352 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
358 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
359 // User language is used for i18n, so we don't want to publicly
360 // cache. Anons are ok, because if they have non-default language
361 // then there's an appropriate Vary header set by whatever set
362 // their non-default language.
363 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
364 "'anon-public-user-private' due to uselang=user\n" );
365 $mode = 'anon-public-user-private';
368 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
369 $this->mCacheMode
= $mode;
373 * Set directives (key/value pairs) for the Cache-Control header.
374 * Boolean values will be formatted as such, by including or omitting
375 * without an equals sign.
377 * Cache control values set here will only be used if the cache mode is not
378 * private, see setCacheMode().
380 * @param array $directives
382 public function setCacheControl( $directives ) {
383 $this->mCacheControl
= $directives +
$this->mCacheControl
;
387 * Create an instance of an output formatter by its name
389 * @param string $format
391 * @return ApiFormatBase
393 public function createPrinterByName( $format ) {
394 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
395 if ( $printer === null ) {
396 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
403 * Execute api request. Any errors will be handled if the API was called by the remote client.
405 public function execute() {
406 if ( $this->mInternalMode
) {
407 $this->executeAction();
409 $this->executeActionWithErrorHandling();
414 * Execute an action, and in case of an error, erase whatever partial results
415 * have been accumulated, and replace it with an error message and a help screen.
417 protected function executeActionWithErrorHandling() {
418 // Verify the CORS header before executing the action
419 if ( !$this->handleCORS() ) {
420 // handleCORS() has sent a 403, abort
424 // Exit here if the request method was OPTIONS
425 // (assume there will be a followup GET or POST)
426 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
430 // In case an error occurs during data output,
431 // clear the output buffer and print just the error information
434 $t = microtime( true );
436 $this->executeAction();
437 } catch ( Exception
$e ) {
438 $this->handleException( $e );
441 // Log the request whether or not there was an error
442 $this->logRequest( microtime( true ) - $t );
444 // Send cache headers after any code which might generate an error, to
445 // avoid sending public cache headers for errors.
446 $this->sendCacheHeaders();
452 * Handle an exception as an API response
455 * @param Exception $e
457 protected function handleException( Exception
$e ) {
458 // Bug 63145: Rollback any open database transactions
459 if ( !( $e instanceof UsageException
) ) {
460 // UsageExceptions are intentional, so don't rollback if that's the case
462 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
463 } catch ( DBError
$e2 ) {
464 // Rollback threw an exception too. Log it, but don't interrupt
465 // our regularly scheduled exception handling.
466 MWExceptionHandler
::logException( $e2 );
470 // Allow extra cleanup and logging
471 Hooks
::run( 'ApiMain::onException', array( $this, $e ) );
474 if ( !( $e instanceof UsageException
) ) {
475 MWExceptionHandler
::logException( $e );
478 // Handle any kind of exception by outputting properly formatted error message.
479 // If this fails, an unhandled exception should be thrown so that global error
480 // handler will process and log it.
482 $errCode = $this->substituteResultWithError( $e );
484 // Error results should not be cached
485 $this->setCacheMode( 'private' );
487 $response = $this->getRequest()->response();
488 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
489 if ( $e->getCode() === 0 ) {
490 $response->header( $headerStr );
492 $response->header( $headerStr, true, $e->getCode() );
495 // Reset and print just the error message
498 // Printer may not be initialized if the extractRequestParams() fails for the main module
499 $this->createErrorPrinter();
502 $this->printResult( true );
503 } catch ( UsageException
$ex ) {
504 // The error printer itself is failing. Try suppressing its request
505 // parameters and redo.
507 'Error printer failed (will retry without params): ' . $ex->getMessage()
509 $this->mPrinter
= null;
510 $this->createErrorPrinter();
511 $this->mPrinter
->forceDefaultParams();
512 $this->printResult( true );
517 * Handle an exception from the ApiBeforeMain hook.
519 * This tries to print the exception as an API response, to be more
520 * friendly to clients. If it fails, it will rethrow the exception.
523 * @param Exception $e
526 public static function handleApiBeforeMainException( Exception
$e ) {
530 $main = new self( RequestContext
::getMain(), false );
531 $main->handleException( $e );
532 } catch ( Exception
$e2 ) {
533 // Nope, even that didn't work. Punt.
537 // Log the request and reset cache headers
538 $main->logRequest( 0 );
539 $main->sendCacheHeaders();
545 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
547 * If no origin parameter is present, nothing happens.
548 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
549 * is set and false is returned.
550 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
551 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
553 * http://www.w3.org/TR/cors/#resource-requests
554 * http://www.w3.org/TR/cors/#resource-preflight-requests
556 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
558 protected function handleCORS() {
559 $originParam = $this->getParameter( 'origin' ); // defaults to null
560 if ( $originParam === null ) {
561 // No origin parameter, nothing to do
565 $request = $this->getRequest();
566 $response = $request->response();
568 // Origin: header is a space-separated list of origins, check all of them
569 $originHeader = $request->getHeader( 'Origin' );
570 if ( $originHeader === false ) {
573 $originHeader = trim( $originHeader );
574 $origins = preg_split( '/\s+/', $originHeader );
577 if ( !in_array( $originParam, $origins ) ) {
578 // origin parameter set but incorrect
579 // Send a 403 response
580 $message = HttpStatus
::getMessage( 403 );
581 $response->header( "HTTP/1.1 403 $message", true, 403 );
582 $response->header( 'Cache-Control: no-cache' );
583 echo "'origin' parameter does not match Origin header\n";
588 $config = $this->getConfig();
589 $matchOrigin = count( $origins ) === 1 && self
::matchOrigin(
591 $config->get( 'CrossSiteAJAXdomains' ),
592 $config->get( 'CrossSiteAJAXdomainExceptions' )
595 if ( $matchOrigin ) {
596 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
597 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
599 // This is a CORS preflight request
600 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
601 // If method is not a case-sensitive match, do not set any additional headers and terminate.
604 // We allow the actual request to send the following headers
605 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
606 if ( $requestedHeaders !== false ) {
607 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
610 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
613 // We only allow the actual request to be GET or POST
614 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
617 $response->header( "Access-Control-Allow-Origin: $originHeader" );
618 $response->header( 'Access-Control-Allow-Credentials: true' );
619 $response->header( "Timing-Allow-Origin: $originHeader" ); # http://www.w3.org/TR/resource-timing/#timing-allow-origin
622 $response->header( 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag' );
626 $this->getOutput()->addVaryHeader( 'Origin' );
631 * Attempt to match an Origin header against a set of rules and a set of exceptions
632 * @param string $value Origin header
633 * @param array $rules Set of wildcard rules
634 * @param array $exceptions Set of wildcard rules
635 * @return bool True if $value matches a rule in $rules and doesn't match
636 * any rules in $exceptions, false otherwise
638 protected static function matchOrigin( $value, $rules, $exceptions ) {
639 foreach ( $rules as $rule ) {
640 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
641 // Rule matches, check exceptions
642 foreach ( $exceptions as $exc ) {
643 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
656 * Attempt to validate the value of Access-Control-Request-Headers against a list
657 * of headers that we allow the follow up request to send.
659 * @param string $requestedHeaders Comma seperated list of HTTP headers
660 * @return bool True if all requested headers are in the list of allowed headers
662 protected static function matchRequestedHeaders( $requestedHeaders ) {
663 if ( trim( $requestedHeaders ) === '' ) {
666 $requestedHeaders = explode( ',', $requestedHeaders );
667 $allowedAuthorHeaders = array_flip( array(
668 /* simple headers (see spec) */
673 /* non-authorable headers in XHR, which are however requested by some UAs */
677 /* MediaWiki whitelist */
680 foreach ( $requestedHeaders as $rHeader ) {
681 $rHeader = strtolower( trim( $rHeader ) );
682 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
683 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
691 * Helper function to convert wildcard string into a regex
695 * @param string $wildcard String with wildcards
696 * @return string Regular expression
698 protected static function wildcardToRegex( $wildcard ) {
699 $wildcard = preg_quote( $wildcard, '/' );
700 $wildcard = str_replace(
706 return "/^https?:\/\/$wildcard$/";
709 protected function sendCacheHeaders() {
710 $response = $this->getRequest()->response();
711 $out = $this->getOutput();
713 $config = $this->getConfig();
715 if ( $config->get( 'VaryOnXFP' ) ) {
716 $out->addVaryHeader( 'X-Forwarded-Proto' );
719 // The logic should be:
720 // $this->mCacheControl['max-age'] is set?
721 // Use it, the module knows better than our guess.
722 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
723 // Use 0 because we can guess caching is probably the wrong thing to do.
724 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
726 if ( isset( $this->mCacheControl
['max-age'] ) ) {
727 $maxage = $this->mCacheControl
['max-age'];
728 } elseif ( ( $this->mModule
&& !$this->mModule
->isWriteMode() ) ||
729 $this->mCacheMode
!== 'private'
731 $maxage = $this->getParameter( 'maxage' );
733 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
735 if ( $this->mCacheMode
== 'private' ) {
736 $response->header( "Cache-Control: $privateCache" );
740 $useXVO = $config->get( 'UseXVO' );
741 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
742 $out->addVaryHeader( 'Cookie' );
743 $response->header( $out->getVaryHeader() );
745 $response->header( $out->getXVO() );
746 if ( $out->haveCacheVaryCookies() ) {
747 // Logged in, mark this request private
748 $response->header( "Cache-Control: $privateCache" );
751 // Logged out, send normal public headers below
752 } elseif ( session_id() != '' ) {
753 // Logged in or otherwise has session (e.g. anonymous users who have edited)
754 // Mark request private
755 $response->header( "Cache-Control: $privateCache" );
758 } // else no XVO and anonymous, send public headers below
761 // Send public headers
762 $response->header( $out->getVaryHeader() );
764 $response->header( $out->getXVO() );
767 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
768 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
769 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
771 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
772 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
775 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
776 // Public cache not requested
777 // Sending a Vary header in this case is harmless, and protects us
778 // against conditional calls of setCacheMaxAge().
779 $response->header( "Cache-Control: $privateCache" );
784 $this->mCacheControl
['public'] = true;
786 // Send an Expires header
787 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
788 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
789 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
791 // Construct the Cache-Control header
794 foreach ( $this->mCacheControl
as $name => $value ) {
795 if ( is_bool( $value ) ) {
797 $ccHeader .= $separator . $name;
801 $ccHeader .= $separator . "$name=$value";
806 $response->header( "Cache-Control: $ccHeader" );
810 * Create the printer for error output
812 private function createErrorPrinter() {
813 if ( !isset( $this->mPrinter
) ) {
814 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
815 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
816 $value = self
::API_DEFAULT_FORMAT
;
818 $this->mPrinter
= $this->createPrinterByName( $value );
821 // Printer may not be able to handle errors. This is particularly
822 // likely if the module returns something for getCustomPrinter().
823 if ( !$this->mPrinter
->canPrintErrors() ) {
824 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
829 * Replace the result data with the information about an exception.
830 * Returns the error code
831 * @param Exception $e
834 protected function substituteResultWithError( $e ) {
835 $result = $this->getResult();
836 $config = $this->getConfig();
838 if ( $e instanceof UsageException
) {
839 // User entered incorrect parameters - generate error response
840 $errMessage = $e->getMessageArray();
841 $link = wfExpandUrl( wfScript( 'api' ) );
842 ApiResult
::setContentValue( $errMessage, 'docref', "See $link for API usage" );
844 // Something is seriously wrong
845 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
846 $info = 'Database query error';
848 $info = "Exception Caught: {$e->getMessage()}";
852 'code' => 'internal_api_error_' . get_class( $e ),
853 'info' => '[' . MWExceptionHandler
::getLogId( $e ) . '] ' . $info,
855 if ( $config->get( 'ShowExceptionDetails' ) ) {
856 ApiResult
::setContentValue(
859 MWExceptionHandler
::getRedactedTraceAsString( $e )
864 // Remember all the warnings to re-add them later
865 $warnings = $result->getResultData( array( 'warnings' ) );
869 $requestid = $this->getParameter( 'requestid' );
870 if ( !is_null( $requestid ) ) {
871 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
873 if ( $config->get( 'ShowHostnames' ) ) {
874 // servedby is especially useful when debugging errors
875 $result->addValue( null, 'servedby', wfHostName(), ApiResult
::NO_SIZE_CHECK
);
877 if ( $warnings !== null ) {
878 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
881 $result->addValue( null, 'error', $errMessage, ApiResult
::NO_SIZE_CHECK
);
883 return $errMessage['code'];
887 * Set up for the execution.
890 protected function setupExecuteAction() {
891 // First add the id to the top element
892 $result = $this->getResult();
893 $requestid = $this->getParameter( 'requestid' );
894 if ( !is_null( $requestid ) ) {
895 $result->addValue( null, 'requestid', $requestid );
898 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
899 $servedby = $this->getParameter( 'servedby' );
901 $result->addValue( null, 'servedby', wfHostName() );
905 if ( $this->getParameter( 'curtimestamp' ) ) {
906 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
907 ApiResult
::NO_SIZE_CHECK
);
910 $params = $this->extractRequestParams();
912 $this->mAction
= $params['action'];
914 if ( !is_string( $this->mAction
) ) {
915 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
922 * Set up the module for response
923 * @return ApiBase The module that will handle this action
924 * @throws MWException
925 * @throws UsageException
927 protected function setupModule() {
928 // Instantiate the module requested by the user
929 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
930 if ( $module === null ) {
931 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
933 $moduleParams = $module->extractRequestParams();
935 // Check token, if necessary
936 if ( $module->needsToken() === true ) {
937 throw new MWException(
938 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
939 "See documentation for ApiBase::needsToken for details."
942 if ( $module->needsToken() ) {
943 if ( !$module->mustBePosted() ) {
944 throw new MWException(
945 "Module '{$module->getModuleName()}' must require POST to use tokens."
949 if ( !isset( $moduleParams['token'] ) ) {
950 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
953 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
955 $module->encodeParamName( 'token' ),
956 $this->getRequest()->getQueryValues()
960 "The '{$module->encodeParamName( 'token' )}' parameter was found in the query string, but must be in the POST body",
965 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
966 $this->dieUsageMsg( 'sessionfailure' );
974 * Check the max lag if necessary
975 * @param ApiBase $module Api module being used
976 * @param array $params Array an array containing the request parameters.
977 * @return bool True on success, false should exit immediately
979 protected function checkMaxLag( $module, $params ) {
980 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
982 $maxLag = $params['maxlag'];
983 list( $host, $lag ) = wfGetLB()->getMaxLag();
984 if ( $lag > $maxLag ) {
985 $response = $this->getRequest()->response();
987 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
988 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
990 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
991 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
994 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
1002 * Check for sufficient permissions to execute
1003 * @param ApiBase $module An Api module
1005 protected function checkExecutePermissions( $module ) {
1006 $user = $this->getUser();
1007 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
1008 !$user->isAllowed( 'read' )
1010 $this->dieUsageMsg( 'readrequired' );
1012 if ( $module->isWriteMode() ) {
1013 if ( !$this->mEnableWrite
) {
1014 $this->dieUsageMsg( 'writedisabled' );
1016 if ( !$user->isAllowed( 'writeapi' ) ) {
1017 $this->dieUsageMsg( 'writerequired' );
1019 if ( wfReadOnly() ) {
1020 $this->dieReadOnly();
1024 // Allow extensions to stop execution for arbitrary reasons.
1026 if ( !Hooks
::run( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
1027 $this->dieUsageMsg( $message );
1032 * Check asserts of the user's rights
1033 * @param array $params
1035 protected function checkAsserts( $params ) {
1036 if ( isset( $params['assert'] ) ) {
1037 $user = $this->getUser();
1038 switch ( $params['assert'] ) {
1040 if ( $user->isAnon() ) {
1041 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
1045 if ( !$user->isAllowed( 'bot' ) ) {
1046 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1054 * Check POST for external response and setup result printer
1055 * @param ApiBase $module An Api module
1056 * @param array $params An array with the request parameters
1058 protected function setupExternalResponse( $module, $params ) {
1059 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
1060 // Module requires POST. GET request might still be allowed
1061 // if $wgDebugApi is true, otherwise fail.
1062 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction
) );
1065 // See if custom printer is used
1066 $this->mPrinter
= $module->getCustomPrinter();
1067 if ( is_null( $this->mPrinter
) ) {
1068 // Create an appropriate printer
1069 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1072 if ( $this->mPrinter
->getNeedsRawData() ) {
1073 $this->getResult()->setRawMode();
1078 * Execute the actual module, without any error handling
1080 protected function executeAction() {
1081 $params = $this->setupExecuteAction();
1082 $module = $this->setupModule();
1083 $this->mModule
= $module;
1085 $this->checkExecutePermissions( $module );
1087 if ( !$this->checkMaxLag( $module, $params ) ) {
1091 if ( !$this->mInternalMode
) {
1092 $this->setupExternalResponse( $module, $params );
1095 $this->checkAsserts( $params );
1099 Hooks
::run( 'APIAfterExecute', array( &$module ) );
1101 $this->reportUnusedParams();
1103 if ( !$this->mInternalMode
) {
1104 //append Debug information
1105 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1107 // Print result data
1108 $this->printResult( false );
1113 * Log the preceding request
1114 * @param int $time Time in seconds
1116 protected function logRequest( $time ) {
1117 $request = $this->getRequest();
1118 $milliseconds = $time === null ?
'?' : round( $time * 1000 );
1120 ' ' . $request->getMethod() .
1121 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1122 ' ' . $request->getIP() .
1123 ' T=' . $milliseconds . 'ms';
1124 foreach ( $this->getParamsUsed() as $name ) {
1125 $value = $request->getVal( $name );
1126 if ( $value === null ) {
1129 $s .= ' ' . $name . '=';
1130 if ( strlen( $value ) > 256 ) {
1131 $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
1132 $s .= $encValue . '[...]';
1134 $s .= $this->encodeRequestLogValue( $value );
1138 wfDebugLog( 'api', $s, 'private' );
1142 * Encode a value in a format suitable for a space-separated log line.
1146 protected function encodeRequestLogValue( $s ) {
1149 $chars = ';@$!*(),/:';
1150 $numChars = strlen( $chars );
1151 for ( $i = 0; $i < $numChars; $i++
) {
1152 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1156 return strtr( rawurlencode( $s ), $table );
1160 * Get the request parameters used in the course of the preceding execute() request
1163 protected function getParamsUsed() {
1164 return array_keys( $this->mParamsUsed
);
1168 * Get a request value, and register the fact that it was used, for logging.
1169 * @param string $name
1170 * @param mixed $default
1173 public function getVal( $name, $default = null ) {
1174 $this->mParamsUsed
[$name] = true;
1176 $ret = $this->getRequest()->getVal( $name );
1177 if ( $ret === null ) {
1178 if ( $this->getRequest()->getArray( $name ) !== null ) {
1179 // See bug 10262 for why we don't just join( '|', ... ) the
1182 "Parameter '$name' uses unsupported PHP array syntax"
1191 * Get a boolean request value, and register the fact that the parameter
1192 * was used, for logging.
1193 * @param string $name
1196 public function getCheck( $name ) {
1197 return $this->getVal( $name, null ) !== null;
1201 * Get a request upload, and register the fact that it was used, for logging.
1204 * @param string $name Parameter name
1205 * @return WebRequestUpload
1207 public function getUpload( $name ) {
1208 $this->mParamsUsed
[$name] = true;
1210 return $this->getRequest()->getUpload( $name );
1214 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1215 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1217 protected function reportUnusedParams() {
1218 $paramsUsed = $this->getParamsUsed();
1219 $allParams = $this->getRequest()->getValueNames();
1221 if ( !$this->mInternalMode
) {
1222 // Printer has not yet executed; don't warn that its parameters are unused
1223 $printerParams = array_map(
1224 array( $this->mPrinter
, 'encodeParamName' ),
1225 array_keys( $this->mPrinter
->getFinalParams() ?
: array() )
1227 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1229 $unusedParams = array_diff( $allParams, $paramsUsed );
1232 if ( count( $unusedParams ) ) {
1233 $s = count( $unusedParams ) > 1 ?
's' : '';
1234 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1239 * Print results using the current printer
1241 * @param bool $isError
1243 protected function printResult( $isError ) {
1244 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1245 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1248 $printer = $this->mPrinter
;
1249 $printer->initPrinter( false );
1250 $printer->execute();
1251 $printer->closePrinter();
1257 public function isReadMode() {
1262 * See ApiBase for description.
1266 public function getAllowedParams() {
1269 ApiBase
::PARAM_DFLT
=> 'help',
1270 ApiBase
::PARAM_TYPE
=> 'submodule',
1273 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1274 ApiBase
::PARAM_TYPE
=> 'submodule',
1277 ApiBase
::PARAM_TYPE
=> 'integer'
1280 ApiBase
::PARAM_TYPE
=> 'integer',
1281 ApiBase
::PARAM_DFLT
=> 0
1284 ApiBase
::PARAM_TYPE
=> 'integer',
1285 ApiBase
::PARAM_DFLT
=> 0
1288 ApiBase
::PARAM_TYPE
=> array( 'user', 'bot' )
1290 'requestid' => null,
1291 'servedby' => false,
1292 'curtimestamp' => false,
1295 ApiBase
::PARAM_DFLT
=> 'user',
1300 /** @see ApiBase::getExamplesMessages() */
1301 protected function getExamplesMessages() {
1304 => 'apihelp-help-example-main',
1305 'action=help&recursivesubmodules=1'
1306 => 'apihelp-help-example-recursive',
1310 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1311 // Wish PHP had an "array_insert_before". Instead, we have to manually
1312 // reindex the array to get 'permissions' in the right place.
1315 foreach ( $oldHelp as $k => $v ) {
1316 if ( $k === 'submodules' ) {
1317 $help['permissions'] = '';
1321 $help['datatypes'] = '';
1322 $help['credits'] = '';
1324 // Fill 'permissions'
1325 $help['permissions'] .= Html
::openElement( 'div',
1326 array( 'class' => 'apihelp-block apihelp-permissions' ) );
1327 $m = $this->msg( 'api-help-permissions' );
1328 if ( !$m->isDisabled() ) {
1329 $help['permissions'] .= Html
::rawElement( 'div', array( 'class' => 'apihelp-block-head' ),
1330 $m->numParams( count( self
::$mRights ) )->parse()
1333 $help['permissions'] .= Html
::openElement( 'dl' );
1334 foreach ( self
::$mRights as $right => $rightMsg ) {
1335 $help['permissions'] .= Html
::element( 'dt', null, $right );
1337 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1338 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1340 $groups = array_map( function ( $group ) {
1341 return $group == '*' ?
'all' : $group;
1342 }, User
::getGroupsWithPermission( $right ) );
1344 $help['permissions'] .= Html
::rawElement( 'dd', null,
1345 $this->msg( 'api-help-permissions-granted-to' )
1346 ->numParams( count( $groups ) )
1347 ->params( $this->getLanguage()->commaList( $groups ) )
1351 $help['permissions'] .= Html
::closeElement( 'dl' );
1352 $help['permissions'] .= Html
::closeElement( 'div' );
1354 // Fill 'datatypes' and 'credits', if applicable
1355 if ( empty( $options['nolead'] ) ) {
1356 $level = $options['headerlevel'];
1357 $tocnumber = &$options['tocnumber'];
1359 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1360 $help['datatypes'] .= Html
::rawelement( 'h' . min( 6, $level ),
1361 array( 'id' => 'main/datatypes', 'class' => 'apihelp-header' ),
1362 Html
::element( 'span', array( 'id' => Sanitizer
::escapeId( 'main/datatypes' ) ) ) .
1365 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1366 if ( !isset( $tocData['main/datatypes'] ) ) {
1367 $tocnumber[$level]++
;
1368 $tocData['main/datatypes'] = array(
1369 'toclevel' => count( $tocnumber ),
1371 'anchor' => 'main/datatypes',
1373 'number' => join( '.', $tocnumber ),
1378 $header = $this->msg( 'api-credits-header' )->parse();
1379 $help['credits'] .= Html
::rawelement( 'h' . min( 6, $level ),
1380 array( 'id' => 'main/credits', 'class' => 'apihelp-header' ),
1381 Html
::element( 'span', array( 'id' => Sanitizer
::escapeId( 'main/credits' ) ) ) .
1384 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1385 if ( !isset( $tocData['main/credits'] ) ) {
1386 $tocnumber[$level]++
;
1387 $tocData['main/credits'] = array(
1388 'toclevel' => count( $tocnumber ),
1390 'anchor' => 'main/credits',
1392 'number' => join( '.', $tocnumber ),
1399 private $mCanApiHighLimits = null;
1402 * Check whether the current user is allowed to use high limits
1405 public function canApiHighLimits() {
1406 if ( !isset( $this->mCanApiHighLimits
) ) {
1407 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1410 return $this->mCanApiHighLimits
;
1414 * Overrides to return this instance's module manager.
1415 * @return ApiModuleManager
1417 public function getModuleManager() {
1418 return $this->mModuleMgr
;
1422 * Fetches the user agent used for this request
1424 * The value will be the combination of the 'Api-User-Agent' header (if
1425 * any) and the standard User-Agent header (if any).
1429 public function getUserAgent() {
1431 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1432 $this->getRequest()->getHeader( 'User-agent' )
1436 /************************************************************************//**
1442 * Sets whether the pretty-printer should format *bold* and $italics$
1444 * @deprecated since 1.25
1447 public function setHelp( $help = true ) {
1448 wfDeprecated( __METHOD__
, '1.25' );
1449 $this->mPrinter
->setHelp( $help );
1453 * Override the parent to generate help messages for all available modules.
1455 * @deprecated since 1.25
1458 public function makeHelpMsg() {
1459 wfDeprecated( __METHOD__
, '1.25' );
1462 // Get help text from cache if present
1463 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1464 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) ) );
1466 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1467 if ( $cacheHelpTimeout > 0 ) {
1468 $cached = $wgMemc->get( $key );
1473 $retval = $this->reallyMakeHelpMsg();
1474 if ( $cacheHelpTimeout > 0 ) {
1475 $wgMemc->set( $key, $retval, $cacheHelpTimeout );
1482 * @deprecated since 1.25
1483 * @return mixed|string
1485 public function reallyMakeHelpMsg() {
1486 wfDeprecated( __METHOD__
, '1.25' );
1489 // Use parent to make default message for the main module
1490 $msg = parent
::makeHelpMsg();
1492 $astriks = str_repeat( '*** ', 14 );
1493 $msg .= "\n\n$astriks Modules $astriks\n\n";
1495 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1496 $module = $this->mModuleMgr
->getModule( $name );
1497 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1499 $msg2 = $module->makeHelpMsg();
1500 if ( $msg2 !== false ) {
1506 $msg .= "\n$astriks Permissions $astriks\n\n";
1507 foreach ( self
::$mRights as $right => $rightMsg ) {
1508 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1509 ->useDatabase( false )
1510 ->inLanguage( 'en' )
1512 $groups = User
::getGroupsWithPermission( $right );
1513 $msg .= "* " . $right . " *\n $rightsMsg" .
1514 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1517 $msg .= "\n$astriks Formats $astriks\n\n";
1518 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1519 $module = $this->mModuleMgr
->getModule( $name );
1520 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1521 $msg2 = $module->makeHelpMsg();
1522 if ( $msg2 !== false ) {
1528 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1529 $credits = str_replace( "\n", "\n ", $credits );
1530 $msg .= "\n*** Credits: ***\n $credits\n";
1536 * @deprecated since 1.25
1537 * @param ApiBase $module
1538 * @param string $paramName What type of request is this? e.g. action,
1539 * query, list, prop, meta, format
1542 public static function makeHelpMsgHeader( $module, $paramName ) {
1543 wfDeprecated( __METHOD__
, '1.25' );
1544 $modulePrefix = $module->getModulePrefix();
1545 if ( strval( $modulePrefix ) !== '' ) {
1546 $modulePrefix = "($modulePrefix) ";
1549 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1553 * Check whether the user wants us to show version information in the API help
1555 * @deprecated since 1.21, always returns false
1557 public function getShowVersions() {
1558 wfDeprecated( __METHOD__
, '1.21' );
1564 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1565 * classes who wish to add their own modules to their lexicon or override the
1566 * behavior of inherent ones.
1568 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1569 * @param string $name The identifier for this module.
1570 * @param ApiBase $class The class where this module is implemented.
1572 protected function addModule( $name, $class ) {
1573 $this->getModuleManager()->addModule( $name, 'action', $class );
1577 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1578 * classes who wish to add to or modify current formatters.
1580 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1581 * @param string $name The identifier for this format.
1582 * @param ApiFormatBase $class The class implementing this format.
1584 protected function addFormat( $name, $class ) {
1585 $this->getModuleManager()->addModule( $name, 'format', $class );
1589 * Get the array mapping module names to class names
1590 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1593 function getModules() {
1594 return $this->getModuleManager()->getNamesWithClasses( 'action' );
1598 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1601 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1604 public function getFormats() {
1605 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1613 * This exception will be thrown when dieUsage is called to stop module execution.
1617 class UsageException
extends MWException
{
1624 private $mExtraData;
1627 * @param string $message
1628 * @param string $codestr
1630 * @param array|null $extradata
1632 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1633 parent
::__construct( $message, $code );
1634 $this->mCodestr
= $codestr;
1635 $this->mExtraData
= $extradata;
1641 public function getCodeString() {
1642 return $this->mCodestr
;
1648 public function getMessageArray() {
1650 'code' => $this->mCodestr
,
1651 'info' => $this->getMessage()
1653 if ( is_array( $this->mExtraData
) ) {
1654 $result = array_merge( $result, $this->mExtraData
);
1663 public function __toString() {
1664 return "{$this->getCodeString()}: {$this->getMessage()}";
1669 * For really cool vim folding this needs to be at the end:
1670 * vim: foldmarker=@{,@} foldmethod=marker