7e3dcff2ee54ce5dda7eb168ced8bada0962f3d9
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 $this->printResult( true );
502 * Handle an exception from the ApiBeforeMain hook.
504 * This tries to print the exception as an API response, to be more
505 * friendly to clients. If it fails, it will rethrow the exception.
508 * @param Exception $e
511 public static function handleApiBeforeMainException( Exception
$e ) {
515 $main = new self( RequestContext
::getMain(), false );
516 $main->handleException( $e );
517 } catch ( Exception
$e2 ) {
518 // Nope, even that didn't work. Punt.
522 // Log the request and reset cache headers
523 $main->logRequest( 0 );
524 $main->sendCacheHeaders();
530 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
532 * If no origin parameter is present, nothing happens.
533 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
534 * is set and false is returned.
535 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
536 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
538 * http://www.w3.org/TR/cors/#resource-requests
539 * http://www.w3.org/TR/cors/#resource-preflight-requests
541 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
543 protected function handleCORS() {
544 $originParam = $this->getParameter( 'origin' ); // defaults to null
545 if ( $originParam === null ) {
546 // No origin parameter, nothing to do
550 $request = $this->getRequest();
551 $response = $request->response();
553 // Origin: header is a space-separated list of origins, check all of them
554 $originHeader = $request->getHeader( 'Origin' );
555 if ( $originHeader === false ) {
558 $originHeader = trim( $originHeader );
559 $origins = preg_split( '/\s+/', $originHeader );
562 if ( !in_array( $originParam, $origins ) ) {
563 // origin parameter set but incorrect
564 // Send a 403 response
565 $message = HttpStatus
::getMessage( 403 );
566 $response->header( "HTTP/1.1 403 $message", true, 403 );
567 $response->header( 'Cache-Control: no-cache' );
568 echo "'origin' parameter does not match Origin header\n";
573 $config = $this->getConfig();
574 $matchOrigin = count( $origins ) === 1 && self
::matchOrigin(
576 $config->get( 'CrossSiteAJAXdomains' ),
577 $config->get( 'CrossSiteAJAXdomainExceptions' )
580 if ( $matchOrigin ) {
581 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
582 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
584 // This is a CORS preflight request
585 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
586 // If method is not a case-sensitive match, do not set any additional headers and terminate.
589 // We allow the actual request to send the following headers
590 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
591 if ( $requestedHeaders !== false ) {
592 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
595 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
598 // We only allow the actual request to be GET or POST
599 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
602 $response->header( "Access-Control-Allow-Origin: $originHeader" );
603 $response->header( 'Access-Control-Allow-Credentials: true' );
604 $response->header( "Timing-Allow-Origin: $originHeader" ); # http://www.w3.org/TR/resource-timing/#timing-allow-origin
607 $response->header( 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag' );
611 $this->getOutput()->addVaryHeader( 'Origin' );
616 * Attempt to match an Origin header against a set of rules and a set of exceptions
617 * @param string $value Origin header
618 * @param array $rules Set of wildcard rules
619 * @param array $exceptions Set of wildcard rules
620 * @return bool True if $value matches a rule in $rules and doesn't match
621 * any rules in $exceptions, false otherwise
623 protected static function matchOrigin( $value, $rules, $exceptions ) {
624 foreach ( $rules as $rule ) {
625 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
626 // Rule matches, check exceptions
627 foreach ( $exceptions as $exc ) {
628 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
641 * Attempt to validate the value of Access-Control-Request-Headers against a list
642 * of headers that we allow the follow up request to send.
644 * @param string $requestedHeaders Comma seperated list of HTTP headers
645 * @return bool True if all requested headers are in the list of allowed headers
647 protected static function matchRequestedHeaders( $requestedHeaders ) {
648 if ( trim( $requestedHeaders ) === '' ) {
651 $requestedHeaders = explode( ',', $requestedHeaders );
652 $allowedAuthorHeaders = array_flip( array(
653 /* simple headers (see spec) */
658 /* non-authorable headers in XHR, which are however requested by some UAs */
662 /* MediaWiki whitelist */
665 foreach ( $requestedHeaders as $rHeader ) {
666 $rHeader = strtolower( trim( $rHeader ) );
667 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
668 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
676 * Helper function to convert wildcard string into a regex
680 * @param string $wildcard String with wildcards
681 * @return string Regular expression
683 protected static function wildcardToRegex( $wildcard ) {
684 $wildcard = preg_quote( $wildcard, '/' );
685 $wildcard = str_replace(
691 return "/^https?:\/\/$wildcard$/";
694 protected function sendCacheHeaders() {
695 $response = $this->getRequest()->response();
696 $out = $this->getOutput();
698 $config = $this->getConfig();
700 if ( $config->get( 'VaryOnXFP' ) ) {
701 $out->addVaryHeader( 'X-Forwarded-Proto' );
704 // The logic should be:
705 // $this->mCacheControl['max-age'] is set?
706 // Use it, the module knows better than our guess.
707 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
708 // Use 0 because we can guess caching is probably the wrong thing to do.
709 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
711 if ( isset( $this->mCacheControl
['max-age'] ) ) {
712 $maxage = $this->mCacheControl
['max-age'];
713 } elseif ( ( $this->mModule
&& !$this->mModule
->isWriteMode() ) ||
714 $this->mCacheMode
!== 'private'
716 $maxage = $this->getParameter( 'maxage' );
718 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
720 if ( $this->mCacheMode
== 'private' ) {
721 $response->header( "Cache-Control: $privateCache" );
725 $useXVO = $config->get( 'UseXVO' );
726 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
727 $out->addVaryHeader( 'Cookie' );
728 $response->header( $out->getVaryHeader() );
730 $response->header( $out->getXVO() );
731 if ( $out->haveCacheVaryCookies() ) {
732 // Logged in, mark this request private
733 $response->header( "Cache-Control: $privateCache" );
736 // Logged out, send normal public headers below
737 } elseif ( session_id() != '' ) {
738 // Logged in or otherwise has session (e.g. anonymous users who have edited)
739 // Mark request private
740 $response->header( "Cache-Control: $privateCache" );
743 } // else no XVO and anonymous, send public headers below
746 // Send public headers
747 $response->header( $out->getVaryHeader() );
749 $response->header( $out->getXVO() );
752 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
753 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
754 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
756 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
757 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
760 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
761 // Public cache not requested
762 // Sending a Vary header in this case is harmless, and protects us
763 // against conditional calls of setCacheMaxAge().
764 $response->header( "Cache-Control: $privateCache" );
769 $this->mCacheControl
['public'] = true;
771 // Send an Expires header
772 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
773 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
774 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
776 // Construct the Cache-Control header
779 foreach ( $this->mCacheControl
as $name => $value ) {
780 if ( is_bool( $value ) ) {
782 $ccHeader .= $separator . $name;
786 $ccHeader .= $separator . "$name=$value";
791 $response->header( "Cache-Control: $ccHeader" );
795 * Replace the result data with the information about an exception.
796 * Returns the error code
797 * @param Exception $e
800 protected function substituteResultWithError( $e ) {
801 $result = $this->getResult();
803 // Printer may not be initialized if the extractRequestParams() fails for the main module
804 if ( !isset( $this->mPrinter
) ) {
805 // The printer has not been created yet. Try to manually get formatter value.
806 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
807 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
808 $value = self
::API_DEFAULT_FORMAT
;
811 $this->mPrinter
= $this->createPrinterByName( $value );
814 // Printer may not be able to handle errors. This is particularly
815 // likely if the module returns something for getCustomPrinter().
816 if ( !$this->mPrinter
->canPrintErrors() ) {
817 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
820 // Update raw mode flag for the selected printer.
821 $result->setRawMode( $this->mPrinter
->getNeedsRawData() );
823 $config = $this->getConfig();
825 if ( $e instanceof UsageException
) {
826 // User entered incorrect parameters - generate error response
827 $errMessage = $e->getMessageArray();
828 $link = wfExpandUrl( wfScript( 'api' ) );
829 ApiResult
::setContentValue( $errMessage, 'docref', "See $link for API usage" );
831 // Something is seriously wrong
832 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
833 $info = 'Database query error';
835 $info = "Exception Caught: {$e->getMessage()}";
839 'code' => 'internal_api_error_' . get_class( $e ),
840 'info' => '[' . MWExceptionHandler
::getLogId( $e ) . '] ' . $info,
842 if ( $config->get( 'ShowExceptionDetails' ) ) {
843 ApiResult
::setContentValue(
846 MWExceptionHandler
::getRedactedTraceAsString( $e )
851 // Remember all the warnings to re-add them later
852 $warnings = $result->getResultData( array( 'warnings' ) );
856 $requestid = $this->getParameter( 'requestid' );
857 if ( !is_null( $requestid ) ) {
858 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
860 if ( $config->get( 'ShowHostnames' ) ) {
861 // servedby is especially useful when debugging errors
862 $result->addValue( null, 'servedby', wfHostName(), ApiResult
::NO_SIZE_CHECK
);
864 if ( $warnings !== null ) {
865 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
868 $result->addValue( null, 'error', $errMessage, ApiResult
::NO_SIZE_CHECK
);
870 return $errMessage['code'];
874 * Set up for the execution.
877 protected function setupExecuteAction() {
878 // First add the id to the top element
879 $result = $this->getResult();
880 $requestid = $this->getParameter( 'requestid' );
881 if ( !is_null( $requestid ) ) {
882 $result->addValue( null, 'requestid', $requestid );
885 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
886 $servedby = $this->getParameter( 'servedby' );
888 $result->addValue( null, 'servedby', wfHostName() );
892 if ( $this->getParameter( 'curtimestamp' ) ) {
893 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
894 ApiResult
::NO_SIZE_CHECK
);
897 $params = $this->extractRequestParams();
899 $this->mAction
= $params['action'];
901 if ( !is_string( $this->mAction
) ) {
902 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
909 * Set up the module for response
910 * @return ApiBase The module that will handle this action
911 * @throws MWException
912 * @throws UsageException
914 protected function setupModule() {
915 // Instantiate the module requested by the user
916 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
917 if ( $module === null ) {
918 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
920 $moduleParams = $module->extractRequestParams();
922 // Check token, if necessary
923 if ( $module->needsToken() === true ) {
924 throw new MWException(
925 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
926 "See documentation for ApiBase::needsToken for details."
929 if ( $module->needsToken() ) {
930 if ( !$module->mustBePosted() ) {
931 throw new MWException(
932 "Module '{$module->getModuleName()}' must require POST to use tokens."
936 if ( !isset( $moduleParams['token'] ) ) {
937 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
940 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
942 $module->encodeParamName( 'token' ),
943 $this->getRequest()->getQueryValues()
947 "The '{$module->encodeParamName( 'token' )}' parameter was found in the query string, but must be in the POST body",
952 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
953 $this->dieUsageMsg( 'sessionfailure' );
961 * Check the max lag if necessary
962 * @param ApiBase $module Api module being used
963 * @param array $params Array an array containing the request parameters.
964 * @return bool True on success, false should exit immediately
966 protected function checkMaxLag( $module, $params ) {
967 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
969 $maxLag = $params['maxlag'];
970 list( $host, $lag ) = wfGetLB()->getMaxLag();
971 if ( $lag > $maxLag ) {
972 $response = $this->getRequest()->response();
974 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
975 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
977 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
978 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
981 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
989 * Check for sufficient permissions to execute
990 * @param ApiBase $module An Api module
992 protected function checkExecutePermissions( $module ) {
993 $user = $this->getUser();
994 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
995 !$user->isAllowed( 'read' )
997 $this->dieUsageMsg( 'readrequired' );
999 if ( $module->isWriteMode() ) {
1000 if ( !$this->mEnableWrite
) {
1001 $this->dieUsageMsg( 'writedisabled' );
1003 if ( !$user->isAllowed( 'writeapi' ) ) {
1004 $this->dieUsageMsg( 'writerequired' );
1006 if ( wfReadOnly() ) {
1007 $this->dieReadOnly();
1011 // Allow extensions to stop execution for arbitrary reasons.
1013 if ( !Hooks
::run( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
1014 $this->dieUsageMsg( $message );
1019 * Check asserts of the user's rights
1020 * @param array $params
1022 protected function checkAsserts( $params ) {
1023 if ( isset( $params['assert'] ) ) {
1024 $user = $this->getUser();
1025 switch ( $params['assert'] ) {
1027 if ( $user->isAnon() ) {
1028 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
1032 if ( !$user->isAllowed( 'bot' ) ) {
1033 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1041 * Check POST for external response and setup result printer
1042 * @param ApiBase $module An Api module
1043 * @param array $params An array with the request parameters
1045 protected function setupExternalResponse( $module, $params ) {
1046 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
1047 // Module requires POST. GET request might still be allowed
1048 // if $wgDebugApi is true, otherwise fail.
1049 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction
) );
1052 // See if custom printer is used
1053 $this->mPrinter
= $module->getCustomPrinter();
1054 if ( is_null( $this->mPrinter
) ) {
1055 // Create an appropriate printer
1056 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1059 if ( $this->mPrinter
->getNeedsRawData() ) {
1060 $this->getResult()->setRawMode();
1065 * Execute the actual module, without any error handling
1067 protected function executeAction() {
1068 $params = $this->setupExecuteAction();
1069 $module = $this->setupModule();
1070 $this->mModule
= $module;
1072 $this->checkExecutePermissions( $module );
1074 if ( !$this->checkMaxLag( $module, $params ) ) {
1078 if ( !$this->mInternalMode
) {
1079 $this->setupExternalResponse( $module, $params );
1082 $this->checkAsserts( $params );
1086 Hooks
::run( 'APIAfterExecute', array( &$module ) );
1088 $this->reportUnusedParams();
1090 if ( !$this->mInternalMode
) {
1091 //append Debug information
1092 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1094 // Print result data
1095 $this->printResult( false );
1100 * Log the preceding request
1101 * @param int $time Time in seconds
1103 protected function logRequest( $time ) {
1104 $request = $this->getRequest();
1105 $milliseconds = $time === null ?
'?' : round( $time * 1000 );
1107 ' ' . $request->getMethod() .
1108 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1109 ' ' . $request->getIP() .
1110 ' T=' . $milliseconds . 'ms';
1111 foreach ( $this->getParamsUsed() as $name ) {
1112 $value = $request->getVal( $name );
1113 if ( $value === null ) {
1116 $s .= ' ' . $name . '=';
1117 if ( strlen( $value ) > 256 ) {
1118 $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
1119 $s .= $encValue . '[...]';
1121 $s .= $this->encodeRequestLogValue( $value );
1125 wfDebugLog( 'api', $s, 'private' );
1129 * Encode a value in a format suitable for a space-separated log line.
1133 protected function encodeRequestLogValue( $s ) {
1136 $chars = ';@$!*(),/:';
1137 $numChars = strlen( $chars );
1138 for ( $i = 0; $i < $numChars; $i++
) {
1139 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1143 return strtr( rawurlencode( $s ), $table );
1147 * Get the request parameters used in the course of the preceding execute() request
1150 protected function getParamsUsed() {
1151 return array_keys( $this->mParamsUsed
);
1155 * Get a request value, and register the fact that it was used, for logging.
1156 * @param string $name
1157 * @param mixed $default
1160 public function getVal( $name, $default = null ) {
1161 $this->mParamsUsed
[$name] = true;
1163 $ret = $this->getRequest()->getVal( $name );
1164 if ( $ret === null ) {
1165 if ( $this->getRequest()->getArray( $name ) !== null ) {
1166 // See bug 10262 for why we don't just join( '|', ... ) the
1169 "Parameter '$name' uses unsupported PHP array syntax"
1178 * Get a boolean request value, and register the fact that the parameter
1179 * was used, for logging.
1180 * @param string $name
1183 public function getCheck( $name ) {
1184 return $this->getVal( $name, null ) !== null;
1188 * Get a request upload, and register the fact that it was used, for logging.
1191 * @param string $name Parameter name
1192 * @return WebRequestUpload
1194 public function getUpload( $name ) {
1195 $this->mParamsUsed
[$name] = true;
1197 return $this->getRequest()->getUpload( $name );
1201 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1202 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1204 protected function reportUnusedParams() {
1205 $paramsUsed = $this->getParamsUsed();
1206 $allParams = $this->getRequest()->getValueNames();
1208 if ( !$this->mInternalMode
) {
1209 // Printer has not yet executed; don't warn that its parameters are unused
1210 $printerParams = array_map(
1211 array( $this->mPrinter
, 'encodeParamName' ),
1212 array_keys( $this->mPrinter
->getFinalParams() ?
: array() )
1214 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1216 $unusedParams = array_diff( $allParams, $paramsUsed );
1219 if ( count( $unusedParams ) ) {
1220 $s = count( $unusedParams ) > 1 ?
's' : '';
1221 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1226 * Print results using the current printer
1228 * @param bool $isError
1230 protected function printResult( $isError ) {
1231 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1232 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1235 $printer = $this->mPrinter
;
1236 $printer->initPrinter( false );
1237 $printer->execute();
1238 $printer->closePrinter();
1244 public function isReadMode() {
1249 * See ApiBase for description.
1253 public function getAllowedParams() {
1256 ApiBase
::PARAM_DFLT
=> 'help',
1257 ApiBase
::PARAM_TYPE
=> 'submodule',
1260 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1261 ApiBase
::PARAM_TYPE
=> 'submodule',
1264 ApiBase
::PARAM_TYPE
=> 'integer'
1267 ApiBase
::PARAM_TYPE
=> 'integer',
1268 ApiBase
::PARAM_DFLT
=> 0
1271 ApiBase
::PARAM_TYPE
=> 'integer',
1272 ApiBase
::PARAM_DFLT
=> 0
1275 ApiBase
::PARAM_TYPE
=> array( 'user', 'bot' )
1277 'requestid' => null,
1278 'servedby' => false,
1279 'curtimestamp' => false,
1282 ApiBase
::PARAM_DFLT
=> 'user',
1287 /** @see ApiBase::getExamplesMessages() */
1288 protected function getExamplesMessages() {
1291 => 'apihelp-help-example-main',
1292 'action=help&recursivesubmodules=1'
1293 => 'apihelp-help-example-recursive',
1297 public function modifyHelp( array &$help, array $options ) {
1298 // Wish PHP had an "array_insert_before". Instead, we have to manually
1299 // reindex the array to get 'permissions' in the right place.
1302 foreach ( $oldHelp as $k => $v ) {
1303 if ( $k === 'submodules' ) {
1304 $help['permissions'] = '';
1308 $help['datatypes'] = '';
1309 $help['credits'] = '';
1311 // Fill 'permissions'
1312 $help['permissions'] .= Html
::openElement( 'div',
1313 array( 'class' => 'apihelp-block apihelp-permissions' ) );
1314 $m = $this->msg( 'api-help-permissions' );
1315 if ( !$m->isDisabled() ) {
1316 $help['permissions'] .= Html
::rawElement( 'div', array( 'class' => 'apihelp-block-head' ),
1317 $m->numParams( count( self
::$mRights ) )->parse()
1320 $help['permissions'] .= Html
::openElement( 'dl' );
1321 foreach ( self
::$mRights as $right => $rightMsg ) {
1322 $help['permissions'] .= Html
::element( 'dt', null, $right );
1324 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1325 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1327 $groups = array_map( function ( $group ) {
1328 return $group == '*' ?
'all' : $group;
1329 }, User
::getGroupsWithPermission( $right ) );
1331 $help['permissions'] .= Html
::rawElement( 'dd', null,
1332 $this->msg( 'api-help-permissions-granted-to' )
1333 ->numParams( count( $groups ) )
1334 ->params( $this->getLanguage()->commaList( $groups ) )
1338 $help['permissions'] .= Html
::closeElement( 'dl' );
1339 $help['permissions'] .= Html
::closeElement( 'div' );
1341 // Fill 'datatypes' and 'credits', if applicable
1342 if ( empty( $options['nolead'] ) ) {
1343 $help['datatypes'] .= Html
::rawelement( 'h' . min( 6, $options['headerlevel'] +
1 ),
1344 array( 'id' => 'main/datatypes', 'class' => 'apihelp-header' ),
1345 Html
::element( 'span', array( 'id' => Sanitizer
::escapeId( 'main/datatypes' ) ) ) .
1346 $this->msg( 'api-help-datatypes-header' )->parse()
1348 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1350 $help['credits'] .= Html
::rawelement( 'h' . min( 6, $options['headerlevel'] +
1 ),
1351 array( 'id' => 'main/credits', 'class' => 'apihelp-header' ),
1352 Html
::element( 'span', array( 'id' => Sanitizer
::escapeId( 'main/credits' ) ) ) .
1353 $this->msg( 'api-credits-header' )->parse()
1355 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1359 private $mCanApiHighLimits = null;
1362 * Check whether the current user is allowed to use high limits
1365 public function canApiHighLimits() {
1366 if ( !isset( $this->mCanApiHighLimits
) ) {
1367 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1370 return $this->mCanApiHighLimits
;
1374 * Overrides to return this instance's module manager.
1375 * @return ApiModuleManager
1377 public function getModuleManager() {
1378 return $this->mModuleMgr
;
1382 * Fetches the user agent used for this request
1384 * The value will be the combination of the 'Api-User-Agent' header (if
1385 * any) and the standard User-Agent header (if any).
1389 public function getUserAgent() {
1391 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1392 $this->getRequest()->getHeader( 'User-agent' )
1396 /************************************************************************//**
1402 * Sets whether the pretty-printer should format *bold* and $italics$
1404 * @deprecated since 1.25
1407 public function setHelp( $help = true ) {
1408 wfDeprecated( __METHOD__
, '1.25' );
1409 $this->mPrinter
->setHelp( $help );
1413 * Override the parent to generate help messages for all available modules.
1415 * @deprecated since 1.25
1418 public function makeHelpMsg() {
1419 wfDeprecated( __METHOD__
, '1.25' );
1422 // Get help text from cache if present
1423 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1424 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) ) );
1426 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1427 if ( $cacheHelpTimeout > 0 ) {
1428 $cached = $wgMemc->get( $key );
1433 $retval = $this->reallyMakeHelpMsg();
1434 if ( $cacheHelpTimeout > 0 ) {
1435 $wgMemc->set( $key, $retval, $cacheHelpTimeout );
1442 * @deprecated since 1.25
1443 * @return mixed|string
1445 public function reallyMakeHelpMsg() {
1446 wfDeprecated( __METHOD__
, '1.25' );
1449 // Use parent to make default message for the main module
1450 $msg = parent
::makeHelpMsg();
1452 $astriks = str_repeat( '*** ', 14 );
1453 $msg .= "\n\n$astriks Modules $astriks\n\n";
1455 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1456 $module = $this->mModuleMgr
->getModule( $name );
1457 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1459 $msg2 = $module->makeHelpMsg();
1460 if ( $msg2 !== false ) {
1466 $msg .= "\n$astriks Permissions $astriks\n\n";
1467 foreach ( self
::$mRights as $right => $rightMsg ) {
1468 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1469 ->useDatabase( false )
1470 ->inLanguage( 'en' )
1472 $groups = User
::getGroupsWithPermission( $right );
1473 $msg .= "* " . $right . " *\n $rightsMsg" .
1474 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1477 $msg .= "\n$astriks Formats $astriks\n\n";
1478 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1479 $module = $this->mModuleMgr
->getModule( $name );
1480 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1481 $msg2 = $module->makeHelpMsg();
1482 if ( $msg2 !== false ) {
1488 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1489 $credits = str_replace( "\n", "\n ", $credits );
1490 $msg .= "\n*** Credits: ***\n $credits\n";
1496 * @deprecated since 1.25
1497 * @param ApiBase $module
1498 * @param string $paramName What type of request is this? e.g. action,
1499 * query, list, prop, meta, format
1502 public static function makeHelpMsgHeader( $module, $paramName ) {
1503 wfDeprecated( __METHOD__
, '1.25' );
1504 $modulePrefix = $module->getModulePrefix();
1505 if ( strval( $modulePrefix ) !== '' ) {
1506 $modulePrefix = "($modulePrefix) ";
1509 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1513 * Check whether the user wants us to show version information in the API help
1515 * @deprecated since 1.21, always returns false
1517 public function getShowVersions() {
1518 wfDeprecated( __METHOD__
, '1.21' );
1524 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1525 * classes who wish to add their own modules to their lexicon or override the
1526 * behavior of inherent ones.
1528 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1529 * @param string $name The identifier for this module.
1530 * @param ApiBase $class The class where this module is implemented.
1532 protected function addModule( $name, $class ) {
1533 $this->getModuleManager()->addModule( $name, 'action', $class );
1537 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1538 * classes who wish to add to or modify current formatters.
1540 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1541 * @param string $name The identifier for this format.
1542 * @param ApiFormatBase $class The class implementing this format.
1544 protected function addFormat( $name, $class ) {
1545 $this->getModuleManager()->addModule( $name, 'format', $class );
1549 * Get the array mapping module names to class names
1550 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1553 function getModules() {
1554 return $this->getModuleManager()->getNamesWithClasses( 'action' );
1558 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1561 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1564 public function getFormats() {
1565 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1573 * This exception will be thrown when dieUsage is called to stop module execution.
1577 class UsageException
extends MWException
{
1584 private $mExtraData;
1587 * @param string $message
1588 * @param string $codestr
1590 * @param array|null $extradata
1592 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1593 parent
::__construct( $message, $code );
1594 $this->mCodestr
= $codestr;
1595 $this->mExtraData
= $extradata;
1601 public function getCodeString() {
1602 return $this->mCodestr
;
1608 public function getMessageArray() {
1610 'code' => $this->mCodestr
,
1611 'info' => $this->getMessage()
1613 if ( is_array( $this->mExtraData
) ) {
1614 $result = array_merge( $result, $this->mExtraData
);
1623 public function __toString() {
1624 return "{$this->getCodeString()}: {$this->getMessage()}";
1629 * For really cool vim folding this needs to be at the end:
1630 * vim: foldmarker=@{,@} foldmethod=marker