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',
93 'mergehistory' => 'ApiMergeHistory',
97 * List of available formats: format name => format class
99 private static $Formats = array(
100 'json' => 'ApiFormatJson',
101 'jsonfm' => 'ApiFormatJson',
102 'php' => 'ApiFormatPhp',
103 'phpfm' => 'ApiFormatPhp',
104 'xml' => 'ApiFormatXml',
105 'xmlfm' => 'ApiFormatXml',
106 'rawfm' => 'ApiFormatJson',
107 'none' => 'ApiFormatNone',
110 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
112 * List of user roles that are specifically relevant to the API.
113 * array( 'right' => array ( 'msg' => 'Some message with a $1',
114 * 'params' => array ( $someVarToSubst ) ),
117 private static $mRights = array(
119 'msg' => 'right-writeapi',
122 'apihighlimits' => array(
123 'msg' => 'api-help-right-apihighlimits',
124 'params' => array( ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
)
127 // @codingStandardsIgnoreEnd
134 private $mModuleMgr, $mResult, $mErrorFormatter, $mContinuationManager;
136 private $mEnableWrite;
137 private $mInternalMode, $mSquidMaxage, $mModule;
139 private $mCacheMode = 'private';
140 private $mCacheControl = array();
141 private $mParamsUsed = array();
144 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
146 * @param IContextSource|WebRequest $context If this is an instance of
147 * FauxRequest, errors are thrown and no printing occurs
148 * @param bool $enableWrite Should be set to true if the api may modify data
150 public function __construct( $context = null, $enableWrite = false ) {
151 if ( $context === null ) {
152 $context = RequestContext
::getMain();
153 } elseif ( $context instanceof WebRequest
) {
156 $context = RequestContext
::getMain();
158 // We set a derivative context so we can change stuff later
159 $this->setContext( new DerivativeContext( $context ) );
161 if ( isset( $request ) ) {
162 $this->getContext()->setRequest( $request );
165 $this->mInternalMode
= ( $this->getRequest() instanceof FauxRequest
);
167 // Special handling for the main module: $parent === $this
168 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
170 if ( !$this->mInternalMode
) {
171 // Impose module restrictions.
172 // If the current user cannot read,
173 // Remove all modules other than login
176 if ( $this->lacksSameOriginSecurity() ) {
177 // If we're in a mode that breaks the same-origin policy, strip
178 // user credentials for security.
179 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
180 $wgUser = new User();
181 $this->getContext()->setUser( $wgUser );
185 $uselang = $this->getParameter( 'uselang' );
186 if ( $uselang === 'user' ) {
187 // Assume the parent context is going to return the user language
188 // for uselang=user (see T85635).
190 if ( $uselang === 'content' ) {
192 $uselang = $wgContLang->getCode();
194 $code = RequestContext
::sanitizeLangCode( $uselang );
195 $this->getContext()->setLanguage( $code );
196 if ( !$this->mInternalMode
) {
198 $wgLang = $this->getContext()->getLanguage();
199 RequestContext
::getMain()->setLanguage( $wgLang );
203 $config = $this->getConfig();
204 $this->mModuleMgr
= new ApiModuleManager( $this );
205 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
206 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
207 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
208 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
210 Hooks
::run( 'ApiMain::moduleManager', array( $this->mModuleMgr
) );
212 $this->mResult
= new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
213 $this->mErrorFormatter
= new ApiErrorFormatter_BackCompat( $this->mResult
);
214 $this->mResult
->setErrorFormatter( $this->mErrorFormatter
);
215 $this->mResult
->setMainForContinuation( $this );
216 $this->mContinuationManager
= null;
217 $this->mEnableWrite
= $enableWrite;
219 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
220 $this->mCommit
= false;
224 * Return true if the API was started by other PHP code using FauxRequest
227 public function isInternalMode() {
228 return $this->mInternalMode
;
232 * Get the ApiResult object associated with current request
236 public function getResult() {
237 return $this->mResult
;
241 * Get the ApiErrorFormatter object associated with current request
242 * @return ApiErrorFormatter
244 public function getErrorFormatter() {
245 return $this->mErrorFormatter
;
249 * Get the continuation manager
250 * @return ApiContinuationManager|null
252 public function getContinuationManager() {
253 return $this->mContinuationManager
;
257 * Set the continuation manager
258 * @param ApiContinuationManager|null
260 public function setContinuationManager( $manager ) {
261 if ( $manager !== null ) {
262 if ( !$manager instanceof ApiContinuationManager
) {
263 throw new InvalidArgumentException( __METHOD__
. ': Was passed ' .
264 is_object( $manager ) ?
get_class( $manager ) : gettype( $manager )
267 if ( $this->mContinuationManager
!== null ) {
268 throw new UnexpectedValueException(
269 __METHOD__
. ': tried to set manager from ' . $manager->getSource() .
270 ' when a manager is already set from ' . $this->mContinuationManager
->getSource()
274 $this->mContinuationManager
= $manager;
278 * Get the API module object. Only works after executeAction()
282 public function getModule() {
283 return $this->mModule
;
287 * Get the result formatter object. Only works after setupExecuteAction()
289 * @return ApiFormatBase
291 public function getPrinter() {
292 return $this->mPrinter
;
296 * Set how long the response should be cached.
300 public function setCacheMaxAge( $maxage ) {
301 $this->setCacheControl( array(
302 'max-age' => $maxage,
303 's-maxage' => $maxage
308 * Set the type of caching headers which will be sent.
310 * @param string $mode One of:
311 * - 'public': Cache this object in public caches, if the maxage or smaxage
312 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
313 * not provided by any of these means, the object will be private.
314 * - 'private': Cache this object only in private client-side caches.
315 * - 'anon-public-user-private': Make this object cacheable for logged-out
316 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
317 * set consistently for a given URL, it cannot be set differently depending on
318 * things like the contents of the database, or whether the user is logged in.
320 * If the wiki does not allow anonymous users to read it, the mode set here
321 * will be ignored, and private caching headers will always be sent. In other words,
322 * the "public" mode is equivalent to saying that the data sent is as public as a page
325 * For user-dependent data, the private mode should generally be used. The
326 * anon-public-user-private mode should only be used where there is a particularly
327 * good performance reason for caching the anonymous response, but where the
328 * response to logged-in users may differ, or may contain private data.
330 * If this function is never called, then the default will be the private mode.
332 public function setCacheMode( $mode ) {
333 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
334 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
336 // Ignore for forwards-compatibility
340 if ( !User
::isEveryoneAllowed( 'read' ) ) {
341 // Private wiki, only private headers
342 if ( $mode !== 'private' ) {
343 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
349 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
350 // User language is used for i18n, so we don't want to publicly
351 // cache. Anons are ok, because if they have non-default language
352 // then there's an appropriate Vary header set by whatever set
353 // their non-default language.
354 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
355 "'anon-public-user-private' due to uselang=user\n" );
356 $mode = 'anon-public-user-private';
359 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
360 $this->mCacheMode
= $mode;
364 * Set directives (key/value pairs) for the Cache-Control header.
365 * Boolean values will be formatted as such, by including or omitting
366 * without an equals sign.
368 * Cache control values set here will only be used if the cache mode is not
369 * private, see setCacheMode().
371 * @param array $directives
373 public function setCacheControl( $directives ) {
374 $this->mCacheControl
= $directives +
$this->mCacheControl
;
378 * Create an instance of an output formatter by its name
380 * @param string $format
382 * @return ApiFormatBase
384 public function createPrinterByName( $format ) {
385 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
386 if ( $printer === null ) {
387 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
394 * Execute api request. Any errors will be handled if the API was called by the remote client.
396 public function execute() {
397 if ( $this->mInternalMode
) {
398 $this->executeAction();
400 $this->executeActionWithErrorHandling();
405 * Execute an action, and in case of an error, erase whatever partial results
406 * have been accumulated, and replace it with an error message and a help screen.
408 protected function executeActionWithErrorHandling() {
409 // Verify the CORS header before executing the action
410 if ( !$this->handleCORS() ) {
411 // handleCORS() has sent a 403, abort
415 // Exit here if the request method was OPTIONS
416 // (assume there will be a followup GET or POST)
417 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
421 // In case an error occurs during data output,
422 // clear the output buffer and print just the error information
423 $obLevel = ob_get_level();
426 $t = microtime( true );
428 $this->executeAction();
430 } catch ( Exception
$e ) {
431 $this->handleException( $e );
435 // Log the request whether or not there was an error
436 $this->logRequest( microtime( true ) - $t );
438 // Commit DBs and send any related cookies and headers
439 MediaWiki
::preOutputCommit( $this->getContext() );
441 // Send cache headers after any code which might generate an error, to
442 // avoid sending public cache headers for errors.
443 $this->sendCacheHeaders( $isError );
445 // Executing the action might have already messed with the output
447 while ( ob_get_level() > $obLevel ) {
453 * Handle an exception as an API response
456 * @param Exception $e
458 protected function handleException( Exception
$e ) {
459 // Bug 63145: Rollback any open database transactions
460 if ( !( $e instanceof UsageException
) ) {
461 // UsageExceptions are intentional, so don't rollback if that's the case
463 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
464 } catch ( DBError
$e2 ) {
465 // Rollback threw an exception too. Log it, but don't interrupt
466 // our regularly scheduled exception handling.
467 MWExceptionHandler
::logException( $e2 );
471 // Allow extra cleanup and logging
472 Hooks
::run( 'ApiMain::onException', array( $this, $e ) );
475 if ( !( $e instanceof UsageException
) ) {
476 MWExceptionHandler
::logException( $e );
479 // Handle any kind of exception by outputting properly formatted error message.
480 // If this fails, an unhandled exception should be thrown so that global error
481 // handler will process and log it.
483 $errCode = $this->substituteResultWithError( $e );
485 // Error results should not be cached
486 $this->setCacheMode( 'private' );
488 $response = $this->getRequest()->response();
489 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
490 if ( $e->getCode() === 0 ) {
491 $response->header( $headerStr );
493 $response->header( $headerStr, true, $e->getCode() );
496 // Reset and print just the error message
499 // Printer may not be initialized if the extractRequestParams() fails for the main module
500 $this->createErrorPrinter();
503 $this->printResult( true );
504 } catch ( UsageException
$ex ) {
505 // The error printer itself is failing. Try suppressing its request
506 // parameters and redo.
508 'Error printer failed (will retry without params): ' . $ex->getMessage()
510 $this->mPrinter
= null;
511 $this->createErrorPrinter();
512 $this->mPrinter
->forceDefaultParams();
513 $this->printResult( true );
518 * Handle an exception from the ApiBeforeMain hook.
520 * This tries to print the exception as an API response, to be more
521 * friendly to clients. If it fails, it will rethrow the exception.
524 * @param Exception $e
527 public static function handleApiBeforeMainException( Exception
$e ) {
531 $main = new self( RequestContext
::getMain(), false );
532 $main->handleException( $e );
533 } catch ( Exception
$e2 ) {
534 // Nope, even that didn't work. Punt.
538 // Log the request and reset cache headers
539 $main->logRequest( 0 );
540 $main->sendCacheHeaders( true );
546 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
548 * If no origin parameter is present, nothing happens.
549 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
550 * is set and false is returned.
551 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
552 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
554 * http://www.w3.org/TR/cors/#resource-requests
555 * http://www.w3.org/TR/cors/#resource-preflight-requests
557 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
559 protected function handleCORS() {
560 $originParam = $this->getParameter( 'origin' ); // defaults to null
561 if ( $originParam === null ) {
562 // No origin parameter, nothing to do
566 $request = $this->getRequest();
567 $response = $request->response();
569 // Origin: header is a space-separated list of origins, check all of them
570 $originHeader = $request->getHeader( 'Origin' );
571 if ( $originHeader === false ) {
574 $originHeader = trim( $originHeader );
575 $origins = preg_split( '/\s+/', $originHeader );
578 if ( !in_array( $originParam, $origins ) ) {
579 // origin parameter set but incorrect
580 // Send a 403 response
581 $response->statusHeader( 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 // http://www.w3.org/TR/resource-timing/#timing-allow-origin
620 $response->header( "Timing-Allow-Origin: $originHeader" );
624 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag'
629 $this->getOutput()->addVaryHeader( 'Origin' );
634 * Attempt to match an Origin header against a set of rules and a set of exceptions
635 * @param string $value Origin header
636 * @param array $rules Set of wildcard rules
637 * @param array $exceptions Set of wildcard rules
638 * @return bool True if $value matches a rule in $rules and doesn't match
639 * any rules in $exceptions, false otherwise
641 protected static function matchOrigin( $value, $rules, $exceptions ) {
642 foreach ( $rules as $rule ) {
643 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
644 // Rule matches, check exceptions
645 foreach ( $exceptions as $exc ) {
646 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
659 * Attempt to validate the value of Access-Control-Request-Headers against a list
660 * of headers that we allow the follow up request to send.
662 * @param string $requestedHeaders Comma seperated list of HTTP headers
663 * @return bool True if all requested headers are in the list of allowed headers
665 protected static function matchRequestedHeaders( $requestedHeaders ) {
666 if ( trim( $requestedHeaders ) === '' ) {
669 $requestedHeaders = explode( ',', $requestedHeaders );
670 $allowedAuthorHeaders = array_flip( array(
671 /* simple headers (see spec) */
676 /* non-authorable headers in XHR, which are however requested by some UAs */
680 /* MediaWiki whitelist */
683 foreach ( $requestedHeaders as $rHeader ) {
684 $rHeader = strtolower( trim( $rHeader ) );
685 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
686 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
694 * Helper function to convert wildcard string into a regex
698 * @param string $wildcard String with wildcards
699 * @return string Regular expression
701 protected static function wildcardToRegex( $wildcard ) {
702 $wildcard = preg_quote( $wildcard, '/' );
703 $wildcard = str_replace(
709 return "/^https?:\/\/$wildcard$/";
713 * Send caching headers
714 * @param boolean $isError Whether an error response is being output
715 * @since 1.26 added $isError parameter
717 protected function sendCacheHeaders( $isError ) {
718 $response = $this->getRequest()->response();
719 $out = $this->getOutput();
721 $config = $this->getConfig();
723 if ( $config->get( 'VaryOnXFP' ) ) {
724 $out->addVaryHeader( 'X-Forwarded-Proto' );
727 if ( !$isError && $this->mModule
&&
728 ( $this->getRequest()->getMethod() === 'GET' ||
$this->getRequest()->getMethod() === 'HEAD' )
730 $etag = $this->mModule
->getConditionalRequestData( 'etag' );
731 if ( $etag !== null ) {
732 $response->header( "ETag: $etag" );
734 $lastMod = $this->mModule
->getConditionalRequestData( 'last-modified' );
735 if ( $lastMod !== null ) {
736 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $lastMod ) );
740 // The logic should be:
741 // $this->mCacheControl['max-age'] is set?
742 // Use it, the module knows better than our guess.
743 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
744 // Use 0 because we can guess caching is probably the wrong thing to do.
745 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
747 if ( isset( $this->mCacheControl
['max-age'] ) ) {
748 $maxage = $this->mCacheControl
['max-age'];
749 } elseif ( ( $this->mModule
&& !$this->mModule
->isWriteMode() ) ||
750 $this->mCacheMode
!== 'private'
752 $maxage = $this->getParameter( 'maxage' );
754 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
756 if ( $this->mCacheMode
== 'private' ) {
757 $response->header( "Cache-Control: $privateCache" );
761 $useKeyHeader = $config->get( 'UseKeyHeader' );
762 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
763 $out->addVaryHeader( 'Cookie' );
764 $response->header( $out->getVaryHeader() );
765 if ( $useKeyHeader ) {
766 $response->header( $out->getKeyHeader() );
767 if ( $out->haveCacheVaryCookies() ) {
768 // Logged in, mark this request private
769 $response->header( "Cache-Control: $privateCache" );
772 // Logged out, send normal public headers below
773 } elseif ( MediaWiki\Session\SessionManager
::getGlobalSession()->isPersistent() ) {
774 // Logged in or otherwise has session (e.g. anonymous users who have edited)
775 // Mark request private
776 $response->header( "Cache-Control: $privateCache" );
779 } // else no Key and anonymous, send public headers below
782 // Send public headers
783 $response->header( $out->getVaryHeader() );
784 if ( $useKeyHeader ) {
785 $response->header( $out->getKeyHeader() );
788 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
789 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
790 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
792 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
793 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
796 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
797 // Public cache not requested
798 // Sending a Vary header in this case is harmless, and protects us
799 // against conditional calls of setCacheMaxAge().
800 $response->header( "Cache-Control: $privateCache" );
805 $this->mCacheControl
['public'] = true;
807 // Send an Expires header
808 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
809 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
810 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
812 // Construct the Cache-Control header
815 foreach ( $this->mCacheControl
as $name => $value ) {
816 if ( is_bool( $value ) ) {
818 $ccHeader .= $separator . $name;
822 $ccHeader .= $separator . "$name=$value";
827 $response->header( "Cache-Control: $ccHeader" );
831 * Create the printer for error output
833 private function createErrorPrinter() {
834 if ( !isset( $this->mPrinter
) ) {
835 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
836 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
837 $value = self
::API_DEFAULT_FORMAT
;
839 $this->mPrinter
= $this->createPrinterByName( $value );
842 // Printer may not be able to handle errors. This is particularly
843 // likely if the module returns something for getCustomPrinter().
844 if ( !$this->mPrinter
->canPrintErrors() ) {
845 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
850 * Replace the result data with the information about an exception.
851 * Returns the error code
852 * @param Exception $e
855 protected function substituteResultWithError( $e ) {
856 $result = $this->getResult();
857 $config = $this->getConfig();
859 if ( $e instanceof UsageException
) {
860 // User entered incorrect parameters - generate error response
861 $errMessage = $e->getMessageArray();
862 $link = wfExpandUrl( wfScript( 'api' ) );
863 ApiResult
::setContentValue( $errMessage, 'docref', "See $link for API usage" );
865 // Something is seriously wrong
866 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
867 $info = 'Database query error';
869 $info = "Exception Caught: {$e->getMessage()}";
873 'code' => 'internal_api_error_' . get_class( $e ),
874 'info' => '[' . MWExceptionHandler
::getLogId( $e ) . '] ' . $info,
876 if ( $config->get( 'ShowExceptionDetails' ) ) {
877 ApiResult
::setContentValue(
880 MWExceptionHandler
::getRedactedTraceAsString( $e )
885 // Remember all the warnings to re-add them later
886 $warnings = $result->getResultData( array( 'warnings' ) );
890 $requestid = $this->getParameter( 'requestid' );
891 if ( !is_null( $requestid ) ) {
892 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
894 if ( $config->get( 'ShowHostnames' ) ) {
895 // servedby is especially useful when debugging errors
896 $result->addValue( null, 'servedby', wfHostname(), ApiResult
::NO_SIZE_CHECK
);
898 if ( $warnings !== null ) {
899 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
902 $result->addValue( null, 'error', $errMessage, ApiResult
::NO_SIZE_CHECK
);
904 return $errMessage['code'];
908 * Set up for the execution.
911 protected function setupExecuteAction() {
912 // First add the id to the top element
913 $result = $this->getResult();
914 $requestid = $this->getParameter( 'requestid' );
915 if ( !is_null( $requestid ) ) {
916 $result->addValue( null, 'requestid', $requestid );
919 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
920 $servedby = $this->getParameter( 'servedby' );
922 $result->addValue( null, 'servedby', wfHostName() );
926 if ( $this->getParameter( 'curtimestamp' ) ) {
927 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
928 ApiResult
::NO_SIZE_CHECK
);
931 $params = $this->extractRequestParams();
933 $this->mAction
= $params['action'];
935 if ( !is_string( $this->mAction
) ) {
936 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
943 * Set up the module for response
944 * @return ApiBase The module that will handle this action
945 * @throws MWException
946 * @throws UsageException
948 protected function setupModule() {
949 // Instantiate the module requested by the user
950 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
951 if ( $module === null ) {
952 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
954 $moduleParams = $module->extractRequestParams();
956 // Check token, if necessary
957 if ( $module->needsToken() === true ) {
958 throw new MWException(
959 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
960 "See documentation for ApiBase::needsToken for details."
963 if ( $module->needsToken() ) {
964 if ( !$module->mustBePosted() ) {
965 throw new MWException(
966 "Module '{$module->getModuleName()}' must require POST to use tokens."
970 if ( !isset( $moduleParams['token'] ) ) {
971 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
974 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
976 $module->encodeParamName( 'token' ),
977 $this->getRequest()->getQueryValues()
981 "The '{$module->encodeParamName( 'token' )}' parameter was " .
982 'found in the query string, but must be in the POST body',
987 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
988 $this->dieUsageMsg( 'sessionfailure' );
996 * Check the max lag if necessary
997 * @param ApiBase $module Api module being used
998 * @param array $params Array an array containing the request parameters.
999 * @return bool True on success, false should exit immediately
1001 protected function checkMaxLag( $module, $params ) {
1002 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1003 $maxLag = $params['maxlag'];
1004 list( $host, $lag ) = wfGetLB()->getMaxLag();
1005 if ( $lag > $maxLag ) {
1006 $response = $this->getRequest()->response();
1008 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1009 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
1011 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1012 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
1015 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
1023 * Check selected RFC 7232 precondition headers
1025 * RFC 7232 envisions a particular model where you send your request to "a
1026 * resource", and for write requests that you can read "the resource" by
1027 * changing the method to GET. When the API receives a GET request, it
1028 * works out even though "the resource" from RFC 7232's perspective might
1029 * be many resources from MediaWiki's perspective. But it totally fails for
1030 * a POST, since what HTTP sees as "the resource" is probably just
1031 * "/api.php" with all the interesting bits in the body.
1033 * Therefore, we only support RFC 7232 precondition headers for GET (and
1034 * HEAD). That means we don't need to bother with If-Match and
1035 * If-Unmodified-Since since they only apply to modification requests.
1037 * And since we don't support Range, If-Range is ignored too.
1040 * @param ApiBase $module Api module being used
1041 * @return bool True on success, false should exit immediately
1043 protected function checkConditionalRequestHeaders( $module ) {
1044 if ( $this->mInternalMode
) {
1045 // No headers to check in internal mode
1049 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1050 // Don't check POSTs
1056 $ifNoneMatch = array_diff(
1057 $this->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
) ?
: array(),
1060 if ( $ifNoneMatch ) {
1061 if ( $ifNoneMatch === array( '*' ) ) {
1062 // API responses always "exist"
1065 $etag = $module->getConditionalRequestData( 'etag' );
1068 if ( $ifNoneMatch && $etag !== null ) {
1069 $test = substr( $etag, 0, 2 ) === 'W/' ?
substr( $etag, 2 ) : $etag;
1070 $match = array_map( function ( $s ) {
1071 return substr( $s, 0, 2 ) === 'W/' ?
substr( $s, 2 ) : $s;
1073 $return304 = in_array( $test, $match, true );
1075 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1077 // Some old browsers sends sizes after the date, like this:
1078 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1080 $i = strpos( $value, ';' );
1081 if ( $i !== false ) {
1082 $value = trim( substr( $value, 0, $i ) );
1085 if ( $value !== '' ) {
1087 $ts = new MWTimestamp( $value );
1089 // RFC 7231 IMF-fixdate
1090 $ts->getTimestamp( TS_RFC2822
) === $value ||
1092 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1093 // asctime (with and without space-padded day)
1094 $ts->format( 'D M j H:i:s Y' ) === $value ||
1095 $ts->format( 'D M j H:i:s Y' ) === $value
1097 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1098 if ( $lastMod !== null ) {
1099 // Mix in some MediaWiki modification times
1100 $modifiedTimes = array(
1102 'user' => $this->getUser()->getTouched(),
1103 'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1105 if ( $this->getConfig()->get( 'UseSquid' ) ) {
1106 // T46570: the core page itself may not change, but resources might
1107 $modifiedTimes['sepoch'] = wfTimestamp(
1108 TS_MW
, time() - $this->getConfig()->get( 'SquidMaxage' )
1111 Hooks
::run( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
1112 $lastMod = max( $modifiedTimes );
1113 $return304 = wfTimestamp( TS_MW
, $lastMod ) <= $ts->getTimestamp( TS_MW
);
1116 } catch ( TimestampException
$e ) {
1117 // Invalid timestamp, ignore it
1123 $this->getRequest()->response()->statusHeader( 304 );
1125 // Avoid outputting the compressed representation of a zero-length body
1126 MediaWiki\
suppressWarnings();
1127 ini_set( 'zlib.output_compression', 0 );
1128 MediaWiki\restoreWarnings
();
1129 wfClearOutputBuffers();
1138 * Check for sufficient permissions to execute
1139 * @param ApiBase $module An Api module
1141 protected function checkExecutePermissions( $module ) {
1142 $user = $this->getUser();
1143 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
1144 !$user->isAllowed( 'read' )
1146 $this->dieUsageMsg( 'readrequired' );
1149 if ( $module->isWriteMode() ) {
1150 if ( !$this->mEnableWrite
) {
1151 $this->dieUsageMsg( 'writedisabled' );
1152 } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1153 $this->dieUsageMsg( 'writerequired' );
1154 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1156 "Promise-Non-Write-API-Action HTTP header cannot be sent to write API modules",
1157 'promised-nonwrite-api'
1161 $this->checkReadOnly( $module );
1164 // Allow extensions to stop execution for arbitrary reasons.
1166 if ( !Hooks
::run( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
1167 $this->dieUsageMsg( $message );
1172 * Check if the DB is read-only for this user
1173 * @param ApiBase $module An Api module
1175 protected function checkReadOnly( $module ) {
1176 if ( wfReadOnly() ) {
1177 $this->dieReadOnly();
1180 if ( $module->isWriteMode()
1181 && in_array( 'bot', $this->getUser()->getGroups() )
1182 && wfGetLB()->getServerCount() > 1
1184 // Figure out how many servers have passed the lag threshold
1186 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1187 foreach ( wfGetLB()->getLagTimes() as $lag ) {
1188 if ( $lag > $lagLimit ) {
1192 // If a majority of slaves are too lagged then disallow writes
1193 $slaveCount = wfGetLB()->getServerCount() - 1;
1194 if ( $numLagged >= ceil( $slaveCount / 2 ) ) {
1195 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1201 array( 'readonlyreason' => "Waiting for $numLagged lagged database(s)" )
1208 * Check asserts of the user's rights
1209 * @param array $params
1211 protected function checkAsserts( $params ) {
1212 if ( isset( $params['assert'] ) ) {
1213 $user = $this->getUser();
1214 switch ( $params['assert'] ) {
1216 if ( $user->isAnon() ) {
1217 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
1221 if ( !$user->isAllowed( 'bot' ) ) {
1222 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1230 * Check POST for external response and setup result printer
1231 * @param ApiBase $module An Api module
1232 * @param array $params An array with the request parameters
1234 protected function setupExternalResponse( $module, $params ) {
1235 $request = $this->getRequest();
1236 if ( !$request->wasPosted() && $module->mustBePosted() ) {
1237 // Module requires POST. GET request might still be allowed
1238 // if $wgDebugApi is true, otherwise fail.
1239 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction
) );
1242 // See if custom printer is used
1243 $this->mPrinter
= $module->getCustomPrinter();
1244 if ( is_null( $this->mPrinter
) ) {
1245 // Create an appropriate printer
1246 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1249 if ( $request->getProtocol() === 'http' && (
1250 $request->getSession()->shouldForceHTTPS() ||
1251 ( $this->getUser()->isLoggedIn() &&
1252 $this->getUser()->requiresHTTPS() )
1254 $this->logFeatureUsage( 'https-expected' );
1255 $this->setWarning( 'HTTP used when HTTPS was expected' );
1260 * Execute the actual module, without any error handling
1262 protected function executeAction() {
1263 $params = $this->setupExecuteAction();
1264 $module = $this->setupModule();
1265 $this->mModule
= $module;
1267 $this->setRequestExpectations( $module );
1269 $this->checkExecutePermissions( $module );
1271 if ( !$this->checkMaxLag( $module, $params ) ) {
1275 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1279 if ( !$this->mInternalMode
) {
1280 $this->setupExternalResponse( $module, $params );
1283 $this->checkAsserts( $params );
1287 Hooks
::run( 'APIAfterExecute', array( &$module ) );
1289 $this->reportUnusedParams();
1291 if ( !$this->mInternalMode
) {
1292 // append Debug information
1293 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1295 // Print result data
1296 $this->printResult( false );
1301 * Set database connection, query, and write expectations given this module request
1302 * @param ApiBase $module
1304 protected function setRequestExpectations( ApiBase
$module ) {
1305 $limits = $this->getConfig()->get( 'TrxProfilerLimits' );
1306 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1307 if ( $this->getRequest()->wasPosted() ) {
1308 if ( $module->isWriteMode() ) {
1309 $trxProfiler->setExpectations( $limits['POST'], __METHOD__
);
1311 $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__
);
1314 $trxProfiler->setExpectations( $limits['GET'], __METHOD__
);
1319 * Log the preceding request
1320 * @param float $time Time in seconds
1322 protected function logRequest( $time ) {
1323 $request = $this->getRequest();
1325 'dt' => date( 'c' ),
1326 'client_ip' => $request->getIP(),
1327 'user_agent' => $this->getUserAgent(),
1328 'wiki' => wfWikiID(),
1329 'time_backend_ms' => round( $time * 1000 ),
1330 'params' => array(),
1333 // Construct space separated message for 'api' log channel
1334 $msg = "API {$request->getMethod()} " .
1335 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1336 " {$logCtx['client_ip']} " .
1337 "T={$logCtx['time_backend_ms']}ms";
1339 foreach ( $this->getParamsUsed() as $name ) {
1340 $value = $request->getVal( $name );
1341 if ( $value === null ) {
1345 if ( strlen( $value ) > 256 ) {
1346 $value = substr( $value, 0, 256 );
1347 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1349 $encValue = $this->encodeRequestLogValue( $value );
1352 $logCtx['params'][$name] = $value;
1353 $msg .= " {$name}={$encValue}";
1356 wfDebugLog( 'api', $msg, 'private' );
1357 // ApiRequest channel is for structured data consumers
1358 wfDebugLog( 'ApiRequest', '', 'private', $logCtx );
1362 * Encode a value in a format suitable for a space-separated log line.
1366 protected function encodeRequestLogValue( $s ) {
1369 $chars = ';@$!*(),/:';
1370 $numChars = strlen( $chars );
1371 for ( $i = 0; $i < $numChars; $i++
) {
1372 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1376 return strtr( rawurlencode( $s ), $table );
1380 * Get the request parameters used in the course of the preceding execute() request
1383 protected function getParamsUsed() {
1384 return array_keys( $this->mParamsUsed
);
1388 * Get a request value, and register the fact that it was used, for logging.
1389 * @param string $name
1390 * @param mixed $default
1393 public function getVal( $name, $default = null ) {
1394 $this->mParamsUsed
[$name] = true;
1396 $ret = $this->getRequest()->getVal( $name );
1397 if ( $ret === null ) {
1398 if ( $this->getRequest()->getArray( $name ) !== null ) {
1399 // See bug 10262 for why we don't just join( '|', ... ) the
1402 "Parameter '$name' uses unsupported PHP array syntax"
1411 * Get a boolean request value, and register the fact that the parameter
1412 * was used, for logging.
1413 * @param string $name
1416 public function getCheck( $name ) {
1417 return $this->getVal( $name, null ) !== null;
1421 * Get a request upload, and register the fact that it was used, for logging.
1424 * @param string $name Parameter name
1425 * @return WebRequestUpload
1427 public function getUpload( $name ) {
1428 $this->mParamsUsed
[$name] = true;
1430 return $this->getRequest()->getUpload( $name );
1434 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1435 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1437 protected function reportUnusedParams() {
1438 $paramsUsed = $this->getParamsUsed();
1439 $allParams = $this->getRequest()->getValueNames();
1441 if ( !$this->mInternalMode
) {
1442 // Printer has not yet executed; don't warn that its parameters are unused
1443 $printerParams = array_map(
1444 array( $this->mPrinter
, 'encodeParamName' ),
1445 array_keys( $this->mPrinter
->getFinalParams() ?
: array() )
1447 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1449 $unusedParams = array_diff( $allParams, $paramsUsed );
1452 if ( count( $unusedParams ) ) {
1453 $s = count( $unusedParams ) > 1 ?
's' : '';
1454 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1459 * Print results using the current printer
1461 * @param bool $isError
1463 protected function printResult( $isError ) {
1464 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1465 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1468 $printer = $this->mPrinter
;
1469 $printer->initPrinter( false );
1470 $printer->execute();
1471 $printer->closePrinter();
1477 public function isReadMode() {
1482 * See ApiBase for description.
1486 public function getAllowedParams() {
1489 ApiBase
::PARAM_DFLT
=> 'help',
1490 ApiBase
::PARAM_TYPE
=> 'submodule',
1493 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1494 ApiBase
::PARAM_TYPE
=> 'submodule',
1497 ApiBase
::PARAM_TYPE
=> 'integer'
1500 ApiBase
::PARAM_TYPE
=> 'integer',
1501 ApiBase
::PARAM_DFLT
=> 0
1504 ApiBase
::PARAM_TYPE
=> 'integer',
1505 ApiBase
::PARAM_DFLT
=> 0
1508 ApiBase
::PARAM_TYPE
=> array( 'user', 'bot' )
1510 'requestid' => null,
1511 'servedby' => false,
1512 'curtimestamp' => false,
1515 ApiBase
::PARAM_DFLT
=> 'user',
1520 /** @see ApiBase::getExamplesMessages() */
1521 protected function getExamplesMessages() {
1524 => 'apihelp-help-example-main',
1525 'action=help&recursivesubmodules=1'
1526 => 'apihelp-help-example-recursive',
1530 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1531 // Wish PHP had an "array_insert_before". Instead, we have to manually
1532 // reindex the array to get 'permissions' in the right place.
1535 foreach ( $oldHelp as $k => $v ) {
1536 if ( $k === 'submodules' ) {
1537 $help['permissions'] = '';
1541 $help['datatypes'] = '';
1542 $help['credits'] = '';
1544 // Fill 'permissions'
1545 $help['permissions'] .= Html
::openElement( 'div',
1546 array( 'class' => 'apihelp-block apihelp-permissions' ) );
1547 $m = $this->msg( 'api-help-permissions' );
1548 if ( !$m->isDisabled() ) {
1549 $help['permissions'] .= Html
::rawElement( 'div', array( 'class' => 'apihelp-block-head' ),
1550 $m->numParams( count( self
::$mRights ) )->parse()
1553 $help['permissions'] .= Html
::openElement( 'dl' );
1554 foreach ( self
::$mRights as $right => $rightMsg ) {
1555 $help['permissions'] .= Html
::element( 'dt', null, $right );
1557 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1558 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1560 $groups = array_map( function ( $group ) {
1561 return $group == '*' ?
'all' : $group;
1562 }, User
::getGroupsWithPermission( $right ) );
1564 $help['permissions'] .= Html
::rawElement( 'dd', null,
1565 $this->msg( 'api-help-permissions-granted-to' )
1566 ->numParams( count( $groups ) )
1567 ->params( $this->getLanguage()->commaList( $groups ) )
1571 $help['permissions'] .= Html
::closeElement( 'dl' );
1572 $help['permissions'] .= Html
::closeElement( 'div' );
1574 // Fill 'datatypes' and 'credits', if applicable
1575 if ( empty( $options['nolead'] ) ) {
1576 $level = $options['headerlevel'];
1577 $tocnumber = &$options['tocnumber'];
1579 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1580 $help['datatypes'] .= Html
::rawElement( 'h' . min( 6, $level ),
1581 array( 'id' => 'main/datatypes', 'class' => 'apihelp-header' ),
1582 Html
::element( 'span', array( 'id' => Sanitizer
::escapeId( 'main/datatypes' ) ) ) .
1585 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1586 if ( !isset( $tocData['main/datatypes'] ) ) {
1587 $tocnumber[$level]++
;
1588 $tocData['main/datatypes'] = array(
1589 'toclevel' => count( $tocnumber ),
1591 'anchor' => 'main/datatypes',
1593 'number' => join( '.', $tocnumber ),
1598 $header = $this->msg( 'api-credits-header' )->parse();
1599 $help['credits'] .= Html
::rawElement( 'h' . min( 6, $level ),
1600 array( 'id' => 'main/credits', 'class' => 'apihelp-header' ),
1601 Html
::element( 'span', array( 'id' => Sanitizer
::escapeId( 'main/credits' ) ) ) .
1604 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1605 if ( !isset( $tocData['main/credits'] ) ) {
1606 $tocnumber[$level]++
;
1607 $tocData['main/credits'] = array(
1608 'toclevel' => count( $tocnumber ),
1610 'anchor' => 'main/credits',
1612 'number' => join( '.', $tocnumber ),
1619 private $mCanApiHighLimits = null;
1622 * Check whether the current user is allowed to use high limits
1625 public function canApiHighLimits() {
1626 if ( !isset( $this->mCanApiHighLimits
) ) {
1627 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1630 return $this->mCanApiHighLimits
;
1634 * Overrides to return this instance's module manager.
1635 * @return ApiModuleManager
1637 public function getModuleManager() {
1638 return $this->mModuleMgr
;
1642 * Fetches the user agent used for this request
1644 * The value will be the combination of the 'Api-User-Agent' header (if
1645 * any) and the standard User-Agent header (if any).
1649 public function getUserAgent() {
1651 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1652 $this->getRequest()->getHeader( 'User-agent' )
1656 /************************************************************************//**
1662 * Sets whether the pretty-printer should format *bold* and $italics$
1664 * @deprecated since 1.25
1667 public function setHelp( $help = true ) {
1668 wfDeprecated( __METHOD__
, '1.25' );
1669 $this->mPrinter
->setHelp( $help );
1673 * Override the parent to generate help messages for all available modules.
1675 * @deprecated since 1.25
1678 public function makeHelpMsg() {
1679 wfDeprecated( __METHOD__
, '1.25' );
1682 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1684 return ObjectCache
::getMainWANInstance()->getWithSetCallback(
1687 $this->getModuleName(),
1688 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) )
1690 $cacheHelpTimeout > 0 ?
$cacheHelpTimeout : WANObjectCache
::TTL_UNCACHEABLE
,
1691 array( $this, 'reallyMakeHelpMsg' )
1696 * @deprecated since 1.25
1697 * @return mixed|string
1699 public function reallyMakeHelpMsg() {
1700 wfDeprecated( __METHOD__
, '1.25' );
1703 // Use parent to make default message for the main module
1704 $msg = parent
::makeHelpMsg();
1706 $astriks = str_repeat( '*** ', 14 );
1707 $msg .= "\n\n$astriks Modules $astriks\n\n";
1709 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1710 $module = $this->mModuleMgr
->getModule( $name );
1711 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1713 $msg2 = $module->makeHelpMsg();
1714 if ( $msg2 !== false ) {
1720 $msg .= "\n$astriks Permissions $astriks\n\n";
1721 foreach ( self
::$mRights as $right => $rightMsg ) {
1722 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1723 ->useDatabase( false )
1724 ->inLanguage( 'en' )
1726 $groups = User
::getGroupsWithPermission( $right );
1727 $msg .= "* " . $right . " *\n $rightsMsg" .
1728 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1731 $msg .= "\n$astriks Formats $astriks\n\n";
1732 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1733 $module = $this->mModuleMgr
->getModule( $name );
1734 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1735 $msg2 = $module->makeHelpMsg();
1736 if ( $msg2 !== false ) {
1742 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1743 $credits = str_replace( "\n", "\n ", $credits );
1744 $msg .= "\n*** Credits: ***\n $credits\n";
1750 * @deprecated since 1.25
1751 * @param ApiBase $module
1752 * @param string $paramName What type of request is this? e.g. action,
1753 * query, list, prop, meta, format
1756 public static function makeHelpMsgHeader( $module, $paramName ) {
1757 wfDeprecated( __METHOD__
, '1.25' );
1758 $modulePrefix = $module->getModulePrefix();
1759 if ( strval( $modulePrefix ) !== '' ) {
1760 $modulePrefix = "($modulePrefix) ";
1763 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1767 * Check whether the user wants us to show version information in the API help
1769 * @deprecated since 1.21, always returns false
1771 public function getShowVersions() {
1772 wfDeprecated( __METHOD__
, '1.21' );
1778 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1779 * classes who wish to add their own modules to their lexicon or override the
1780 * behavior of inherent ones.
1782 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1783 * @param string $name The identifier for this module.
1784 * @param ApiBase $class The class where this module is implemented.
1786 protected function addModule( $name, $class ) {
1787 $this->getModuleManager()->addModule( $name, 'action', $class );
1791 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1792 * classes who wish to add to or modify current formatters.
1794 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1795 * @param string $name The identifier for this format.
1796 * @param ApiFormatBase $class The class implementing this format.
1798 protected function addFormat( $name, $class ) {
1799 $this->getModuleManager()->addModule( $name, 'format', $class );
1803 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1806 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1809 public function getFormats() {
1810 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1818 * This exception will be thrown when dieUsage is called to stop module execution.
1822 class UsageException
extends MWException
{
1829 private $mExtraData;
1832 * @param string $message
1833 * @param string $codestr
1835 * @param array|null $extradata
1837 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1838 parent
::__construct( $message, $code );
1839 $this->mCodestr
= $codestr;
1840 $this->mExtraData
= $extradata;
1846 public function getCodeString() {
1847 return $this->mCodestr
;
1853 public function getMessageArray() {
1855 'code' => $this->mCodestr
,
1856 'info' => $this->getMessage()
1858 if ( is_array( $this->mExtraData
) ) {
1859 $result = array_merge( $result, $this->mExtraData
);
1868 public function __toString() {
1869 return "{$this->getCodeString()}: {$this->getMessage()}";
1874 * For really cool vim folding this needs to be at the end:
1875 * vim: foldmarker=@{,@} foldmethod=marker