5 * Created on Sep 4, 2006
7 * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com"
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
29 * This is the main API class, used for both external and internal processing.
30 * When executed, it will create the requested formatter object,
31 * instantiate and execute an object associated with the needed action,
32 * and use formatter to print results.
33 * In case of an exception, an error message will be printed using the same formatter.
35 * To use API from another application, run it using FauxRequest object, in which
36 * case any internal exceptions will not be handled but passed up to the caller.
37 * After successful execution, use getResult() for the resulting data.
41 class ApiMain
extends ApiBase
{
43 * When no format parameter is given, this format will be used
45 const API_DEFAULT_FORMAT
= 'jsonfm';
48 * List of available modules: action name => module class
50 private static $Modules = array(
51 'login' => 'ApiLogin',
52 'logout' => 'ApiLogout',
53 'createaccount' => 'ApiCreateAccount',
54 'query' => 'ApiQuery',
55 'expandtemplates' => 'ApiExpandTemplates',
56 'parse' => 'ApiParse',
57 'stashedit' => 'ApiStashEdit',
58 'opensearch' => 'ApiOpenSearch',
59 'feedcontributions' => 'ApiFeedContributions',
60 'feedrecentchanges' => 'ApiFeedRecentChanges',
61 'feedwatchlist' => 'ApiFeedWatchlist',
63 'paraminfo' => 'ApiParamInfo',
65 'compare' => 'ApiComparePages',
66 'tokens' => 'ApiTokens',
67 'checktoken' => 'ApiCheckToken',
70 'purge' => 'ApiPurge',
71 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
72 'rollback' => 'ApiRollback',
73 'delete' => 'ApiDelete',
74 'undelete' => 'ApiUndelete',
75 'protect' => 'ApiProtect',
76 'block' => 'ApiBlock',
77 'unblock' => 'ApiUnblock',
79 'edit' => 'ApiEditPage',
80 'upload' => 'ApiUpload',
81 'filerevert' => 'ApiFileRevert',
82 'emailuser' => 'ApiEmailUser',
83 'watch' => 'ApiWatch',
84 'patrol' => 'ApiPatrol',
85 'import' => 'ApiImport',
86 'clearhasmsg' => 'ApiClearHasMsg',
87 'userrights' => 'ApiUserrights',
88 'options' => 'ApiOptions',
89 'imagerotate' => 'ApiImageRotate',
90 'revisiondelete' => 'ApiRevisionDelete',
91 'managetags' => 'ApiManageTags',
96 * List of available formats: format name => format class
98 private static $Formats = array(
99 'json' => 'ApiFormatJson',
100 'jsonfm' => 'ApiFormatJson',
101 'php' => 'ApiFormatPhp',
102 'phpfm' => 'ApiFormatPhp',
103 'xml' => 'ApiFormatXml',
104 'xmlfm' => 'ApiFormatXml',
105 'yaml' => 'ApiFormatYaml',
106 'yamlfm' => 'ApiFormatYaml',
107 'rawfm' => 'ApiFormatJson',
108 'txt' => 'ApiFormatTxt',
109 'txtfm' => 'ApiFormatTxt',
110 'dbg' => 'ApiFormatDbg',
111 'dbgfm' => 'ApiFormatDbg',
112 'none' => 'ApiFormatNone',
115 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
117 * List of user roles that are specifically relevant to the API.
118 * array( 'right' => array ( 'msg' => 'Some message with a $1',
119 * 'params' => array ( $someVarToSubst ) ),
122 private static $mRights = array(
124 'msg' => 'right-writeapi',
127 'apihighlimits' => array(
128 'msg' => 'api-help-right-apihighlimits',
129 'params' => array( ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
)
132 // @codingStandardsIgnoreEnd
139 private $mModuleMgr, $mResult, $mErrorFormatter, $mContinuationManager;
141 private $mEnableWrite;
142 private $mInternalMode, $mSquidMaxage, $mModule;
144 private $mCacheMode = 'private';
145 private $mCacheControl = array();
146 private $mParamsUsed = array();
149 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
151 * @param IContextSource|WebRequest $context If this is an instance of
152 * FauxRequest, errors are thrown and no printing occurs
153 * @param bool $enableWrite Should be set to true if the api may modify data
155 public function __construct( $context = null, $enableWrite = false ) {
156 if ( $context === null ) {
157 $context = RequestContext
::getMain();
158 } elseif ( $context instanceof WebRequest
) {
161 $context = RequestContext
::getMain();
163 // We set a derivative context so we can change stuff later
164 $this->setContext( new DerivativeContext( $context ) );
166 if ( isset( $request ) ) {
167 $this->getContext()->setRequest( $request );
170 $this->mInternalMode
= ( $this->getRequest() instanceof FauxRequest
);
172 // Special handling for the main module: $parent === $this
173 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
175 if ( !$this->mInternalMode
) {
176 // Impose module restrictions.
177 // If the current user cannot read,
178 // Remove all modules other than login
181 if ( $this->lacksSameOriginSecurity() ) {
182 // If we're in a mode that breaks the same-origin policy, strip
183 // user credentials for security.
184 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
185 $wgUser = new User();
186 $this->getContext()->setUser( $wgUser );
190 $uselang = $this->getParameter( 'uselang' );
191 if ( $uselang === 'user' ) {
192 // Assume the parent context is going to return the user language
193 // for uselang=user (see T85635).
195 if ( $uselang === 'content' ) {
197 $uselang = $wgContLang->getCode();
199 $code = RequestContext
::sanitizeLangCode( $uselang );
200 $this->getContext()->setLanguage( $code );
201 if ( !$this->mInternalMode
) {
203 $wgLang = $this->getContext()->getLanguage();
204 RequestContext
::getMain()->setLanguage( $wgLang );
208 $config = $this->getConfig();
209 $this->mModuleMgr
= new ApiModuleManager( $this );
210 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
211 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
212 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
213 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
215 Hooks
::run( 'ApiMain::moduleManager', array( $this->mModuleMgr
) );
217 $this->mResult
= new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
218 $this->mErrorFormatter
= new ApiErrorFormatter_BackCompat( $this->mResult
);
219 $this->mResult
->setErrorFormatter( $this->mErrorFormatter
);
220 $this->mResult
->setMainForContinuation( $this );
221 $this->mContinuationManager
= null;
222 $this->mEnableWrite
= $enableWrite;
224 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
225 $this->mCommit
= false;
229 * Return true if the API was started by other PHP code using FauxRequest
232 public function isInternalMode() {
233 return $this->mInternalMode
;
237 * Get the ApiResult object associated with current request
241 public function getResult() {
242 return $this->mResult
;
246 * Get the ApiErrorFormatter object associated with current request
247 * @return ApiErrorFormatter
249 public function getErrorFormatter() {
250 return $this->mErrorFormatter
;
254 * Get the continuation manager
255 * @return ApiContinuationManager|null
257 public function getContinuationManager() {
258 return $this->mContinuationManager
;
262 * Set the continuation manager
263 * @param ApiContinuationManager|null
265 public function setContinuationManager( $manager ) {
266 if ( $manager !== null ) {
267 if ( !$manager instanceof ApiContinuationManager
) {
268 throw new InvalidArgumentException( __METHOD__
. ': Was passed ' .
269 is_object( $manager ) ?
get_class( $manager ) : gettype( $manager )
272 if ( $this->mContinuationManager
!== null ) {
273 throw new UnexpectedValueException(
274 __METHOD__
. ': tried to set manager from ' . $manager->getSource() .
275 ' when a manager is already set from ' . $this->mContinuationManager
->getSource()
279 $this->mContinuationManager
= $manager;
283 * Get the API module object. Only works after executeAction()
287 public function getModule() {
288 return $this->mModule
;
292 * Get the result formatter object. Only works after setupExecuteAction()
294 * @return ApiFormatBase
296 public function getPrinter() {
297 return $this->mPrinter
;
301 * Set how long the response should be cached.
305 public function setCacheMaxAge( $maxage ) {
306 $this->setCacheControl( array(
307 'max-age' => $maxage,
308 's-maxage' => $maxage
313 * Set the type of caching headers which will be sent.
315 * @param string $mode One of:
316 * - 'public': Cache this object in public caches, if the maxage or smaxage
317 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
318 * not provided by any of these means, the object will be private.
319 * - 'private': Cache this object only in private client-side caches.
320 * - 'anon-public-user-private': Make this object cacheable for logged-out
321 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
322 * set consistently for a given URL, it cannot be set differently depending on
323 * things like the contents of the database, or whether the user is logged in.
325 * If the wiki does not allow anonymous users to read it, the mode set here
326 * will be ignored, and private caching headers will always be sent. In other words,
327 * the "public" mode is equivalent to saying that the data sent is as public as a page
330 * For user-dependent data, the private mode should generally be used. The
331 * anon-public-user-private mode should only be used where there is a particularly
332 * good performance reason for caching the anonymous response, but where the
333 * response to logged-in users may differ, or may contain private data.
335 * If this function is never called, then the default will be the private mode.
337 public function setCacheMode( $mode ) {
338 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
339 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
341 // Ignore for forwards-compatibility
345 if ( !User
::isEveryoneAllowed( 'read' ) ) {
346 // Private wiki, only private headers
347 if ( $mode !== 'private' ) {
348 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
354 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
355 // User language is used for i18n, so we don't want to publicly
356 // cache. Anons are ok, because if they have non-default language
357 // then there's an appropriate Vary header set by whatever set
358 // their non-default language.
359 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
360 "'anon-public-user-private' due to uselang=user\n" );
361 $mode = 'anon-public-user-private';
364 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
365 $this->mCacheMode
= $mode;
369 * Set directives (key/value pairs) for the Cache-Control header.
370 * Boolean values will be formatted as such, by including or omitting
371 * without an equals sign.
373 * Cache control values set here will only be used if the cache mode is not
374 * private, see setCacheMode().
376 * @param array $directives
378 public function setCacheControl( $directives ) {
379 $this->mCacheControl
= $directives +
$this->mCacheControl
;
383 * Create an instance of an output formatter by its name
385 * @param string $format
387 * @return ApiFormatBase
389 public function createPrinterByName( $format ) {
390 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
391 if ( $printer === null ) {
392 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
399 * Execute api request. Any errors will be handled if the API was called by the remote client.
401 public function execute() {
402 if ( $this->mInternalMode
) {
403 $this->executeAction();
405 $this->executeActionWithErrorHandling();
410 * Execute an action, and in case of an error, erase whatever partial results
411 * have been accumulated, and replace it with an error message and a help screen.
413 protected function executeActionWithErrorHandling() {
414 // Verify the CORS header before executing the action
415 if ( !$this->handleCORS() ) {
416 // handleCORS() has sent a 403, abort
420 // Exit here if the request method was OPTIONS
421 // (assume there will be a followup GET or POST)
422 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
426 // In case an error occurs during data output,
427 // clear the output buffer and print just the error information
428 $obLevel = ob_get_level();
431 $t = microtime( true );
433 $this->executeAction();
435 } catch ( Exception
$e ) {
436 $this->handleException( $e );
440 // Log the request whether or not there was an error
441 $this->logRequest( microtime( true ) - $t );
443 // Send cache headers after any code which might generate an error, to
444 // avoid sending public cache headers for errors.
445 $this->sendCacheHeaders( $isError );
447 // Executing the action might have already messed with the output
449 while ( ob_get_level() > $obLevel ) {
455 * Handle an exception as an API response
458 * @param Exception $e
460 protected function handleException( Exception
$e ) {
461 // Bug 63145: Rollback any open database transactions
462 if ( !( $e instanceof UsageException
) ) {
463 // UsageExceptions are intentional, so don't rollback if that's the case
465 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
466 } catch ( DBError
$e2 ) {
467 // Rollback threw an exception too. Log it, but don't interrupt
468 // our regularly scheduled exception handling.
469 MWExceptionHandler
::logException( $e2 );
473 // Allow extra cleanup and logging
474 Hooks
::run( 'ApiMain::onException', array( $this, $e ) );
477 if ( !( $e instanceof UsageException
) ) {
478 MWExceptionHandler
::logException( $e );
481 // Handle any kind of exception by outputting properly formatted error message.
482 // If this fails, an unhandled exception should be thrown so that global error
483 // handler will process and log it.
485 $errCode = $this->substituteResultWithError( $e );
487 // Error results should not be cached
488 $this->setCacheMode( 'private' );
490 $response = $this->getRequest()->response();
491 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
492 if ( $e->getCode() === 0 ) {
493 $response->header( $headerStr );
495 $response->header( $headerStr, true, $e->getCode() );
498 // Reset and print just the error message
501 // Printer may not be initialized if the extractRequestParams() fails for the main module
502 $this->createErrorPrinter();
505 $this->printResult( true );
506 } catch ( UsageException
$ex ) {
507 // The error printer itself is failing. Try suppressing its request
508 // parameters and redo.
510 'Error printer failed (will retry without params): ' . $ex->getMessage()
512 $this->mPrinter
= null;
513 $this->createErrorPrinter();
514 $this->mPrinter
->forceDefaultParams();
515 $this->printResult( true );
520 * Handle an exception from the ApiBeforeMain hook.
522 * This tries to print the exception as an API response, to be more
523 * friendly to clients. If it fails, it will rethrow the exception.
526 * @param Exception $e
529 public static function handleApiBeforeMainException( Exception
$e ) {
533 $main = new self( RequestContext
::getMain(), false );
534 $main->handleException( $e );
535 } catch ( Exception
$e2 ) {
536 // Nope, even that didn't work. Punt.
540 // Log the request and reset cache headers
541 $main->logRequest( 0 );
542 $main->sendCacheHeaders( true );
548 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
550 * If no origin parameter is present, nothing happens.
551 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
552 * is set and false is returned.
553 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
554 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
556 * http://www.w3.org/TR/cors/#resource-requests
557 * http://www.w3.org/TR/cors/#resource-preflight-requests
559 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
561 protected function handleCORS() {
562 $originParam = $this->getParameter( 'origin' ); // defaults to null
563 if ( $originParam === null ) {
564 // No origin parameter, nothing to do
568 $request = $this->getRequest();
569 $response = $request->response();
571 // Origin: header is a space-separated list of origins, check all of them
572 $originHeader = $request->getHeader( 'Origin' );
573 if ( $originHeader === false ) {
576 $originHeader = trim( $originHeader );
577 $origins = preg_split( '/\s+/', $originHeader );
580 if ( !in_array( $originParam, $origins ) ) {
581 // origin parameter set but incorrect
582 // Send a 403 response
583 $response->statusHeader( 403 );
584 $response->header( 'Cache-Control: no-cache' );
585 echo "'origin' parameter does not match Origin header\n";
590 $config = $this->getConfig();
591 $matchOrigin = count( $origins ) === 1 && self
::matchOrigin(
593 $config->get( 'CrossSiteAJAXdomains' ),
594 $config->get( 'CrossSiteAJAXdomainExceptions' )
597 if ( $matchOrigin ) {
598 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
599 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
601 // This is a CORS preflight request
602 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
603 // If method is not a case-sensitive match, do not set any additional headers and terminate.
606 // We allow the actual request to send the following headers
607 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
608 if ( $requestedHeaders !== false ) {
609 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
612 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
615 // We only allow the actual request to be GET or POST
616 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
619 $response->header( "Access-Control-Allow-Origin: $originHeader" );
620 $response->header( 'Access-Control-Allow-Credentials: true' );
621 $response->header( "Timing-Allow-Origin: $originHeader" ); # http://www.w3.org/TR/resource-timing/#timing-allow-origin
624 $response->header( 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag' );
628 $this->getOutput()->addVaryHeader( 'Origin' );
633 * Attempt to match an Origin header against a set of rules and a set of exceptions
634 * @param string $value Origin header
635 * @param array $rules Set of wildcard rules
636 * @param array $exceptions Set of wildcard rules
637 * @return bool True if $value matches a rule in $rules and doesn't match
638 * any rules in $exceptions, false otherwise
640 protected static function matchOrigin( $value, $rules, $exceptions ) {
641 foreach ( $rules as $rule ) {
642 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
643 // Rule matches, check exceptions
644 foreach ( $exceptions as $exc ) {
645 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
658 * Attempt to validate the value of Access-Control-Request-Headers against a list
659 * of headers that we allow the follow up request to send.
661 * @param string $requestedHeaders Comma seperated list of HTTP headers
662 * @return bool True if all requested headers are in the list of allowed headers
664 protected static function matchRequestedHeaders( $requestedHeaders ) {
665 if ( trim( $requestedHeaders ) === '' ) {
668 $requestedHeaders = explode( ',', $requestedHeaders );
669 $allowedAuthorHeaders = array_flip( array(
670 /* simple headers (see spec) */
675 /* non-authorable headers in XHR, which are however requested by some UAs */
679 /* MediaWiki whitelist */
682 foreach ( $requestedHeaders as $rHeader ) {
683 $rHeader = strtolower( trim( $rHeader ) );
684 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
685 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
693 * Helper function to convert wildcard string into a regex
697 * @param string $wildcard String with wildcards
698 * @return string Regular expression
700 protected static function wildcardToRegex( $wildcard ) {
701 $wildcard = preg_quote( $wildcard, '/' );
702 $wildcard = str_replace(
708 return "/^https?:\/\/$wildcard$/";
712 * Send caching headers
713 * @param boolean $isError Whether an error response is being output
714 * @since 1.26 added $isError parameter
716 protected function sendCacheHeaders( $isError ) {
717 $response = $this->getRequest()->response();
718 $out = $this->getOutput();
720 $config = $this->getConfig();
722 if ( $config->get( 'VaryOnXFP' ) ) {
723 $out->addVaryHeader( 'X-Forwarded-Proto' );
726 if ( !$isError && $this->mModule
&&
727 ( $this->getRequest()->getMethod() === 'GET' ||
$this->getRequest()->getMethod() === 'HEAD' )
729 $etag = $this->mModule
->getConditionalRequestData( 'etag' );
730 if ( $etag !== null ) {
731 $response->header( "ETag: $etag" );
733 $lastMod = $this->mModule
->getConditionalRequestData( 'last-modified' );
734 if ( $lastMod !== null ) {
735 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $lastMod ) );
739 // The logic should be:
740 // $this->mCacheControl['max-age'] is set?
741 // Use it, the module knows better than our guess.
742 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
743 // Use 0 because we can guess caching is probably the wrong thing to do.
744 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
746 if ( isset( $this->mCacheControl
['max-age'] ) ) {
747 $maxage = $this->mCacheControl
['max-age'];
748 } elseif ( ( $this->mModule
&& !$this->mModule
->isWriteMode() ) ||
749 $this->mCacheMode
!== 'private'
751 $maxage = $this->getParameter( 'maxage' );
753 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
755 if ( $this->mCacheMode
== 'private' ) {
756 $response->header( "Cache-Control: $privateCache" );
760 $useXVO = $config->get( 'UseXVO' );
761 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
762 $out->addVaryHeader( 'Cookie' );
763 $response->header( $out->getVaryHeader() );
765 $response->header( $out->getXVO() );
766 if ( $out->haveCacheVaryCookies() ) {
767 // Logged in, mark this request private
768 $response->header( "Cache-Control: $privateCache" );
771 // Logged out, send normal public headers below
772 } elseif ( session_id() != '' ) {
773 // Logged in or otherwise has session (e.g. anonymous users who have edited)
774 // Mark request private
775 $response->header( "Cache-Control: $privateCache" );
778 } // else no XVO and anonymous, send public headers below
781 // Send public headers
782 $response->header( $out->getVaryHeader() );
784 $response->header( $out->getXVO() );
787 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
788 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
789 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
791 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
792 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
795 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
796 // Public cache not requested
797 // Sending a Vary header in this case is harmless, and protects us
798 // against conditional calls of setCacheMaxAge().
799 $response->header( "Cache-Control: $privateCache" );
804 $this->mCacheControl
['public'] = true;
806 // Send an Expires header
807 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
808 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
809 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
811 // Construct the Cache-Control header
814 foreach ( $this->mCacheControl
as $name => $value ) {
815 if ( is_bool( $value ) ) {
817 $ccHeader .= $separator . $name;
821 $ccHeader .= $separator . "$name=$value";
826 $response->header( "Cache-Control: $ccHeader" );
830 * Create the printer for error output
832 private function createErrorPrinter() {
833 if ( !isset( $this->mPrinter
) ) {
834 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
835 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
836 $value = self
::API_DEFAULT_FORMAT
;
838 $this->mPrinter
= $this->createPrinterByName( $value );
841 // Printer may not be able to handle errors. This is particularly
842 // likely if the module returns something for getCustomPrinter().
843 if ( !$this->mPrinter
->canPrintErrors() ) {
844 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
849 * Replace the result data with the information about an exception.
850 * Returns the error code
851 * @param Exception $e
854 protected function substituteResultWithError( $e ) {
855 $result = $this->getResult();
856 $config = $this->getConfig();
858 if ( $e instanceof UsageException
) {
859 // User entered incorrect parameters - generate error response
860 $errMessage = $e->getMessageArray();
861 $link = wfExpandUrl( wfScript( 'api' ) );
862 ApiResult
::setContentValue( $errMessage, 'docref', "See $link for API usage" );
864 // Something is seriously wrong
865 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
866 $info = 'Database query error';
868 $info = "Exception Caught: {$e->getMessage()}";
872 'code' => 'internal_api_error_' . get_class( $e ),
873 'info' => '[' . MWExceptionHandler
::getLogId( $e ) . '] ' . $info,
875 if ( $config->get( 'ShowExceptionDetails' ) ) {
876 ApiResult
::setContentValue(
879 MWExceptionHandler
::getRedactedTraceAsString( $e )
884 // Remember all the warnings to re-add them later
885 $warnings = $result->getResultData( array( 'warnings' ) );
889 $requestid = $this->getParameter( 'requestid' );
890 if ( !is_null( $requestid ) ) {
891 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
893 if ( $config->get( 'ShowHostnames' ) ) {
894 // servedby is especially useful when debugging errors
895 $result->addValue( null, 'servedby', wfHostName(), ApiResult
::NO_SIZE_CHECK
);
897 if ( $warnings !== null ) {
898 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
901 $result->addValue( null, 'error', $errMessage, ApiResult
::NO_SIZE_CHECK
);
903 return $errMessage['code'];
907 * Set up for the execution.
910 protected function setupExecuteAction() {
911 // First add the id to the top element
912 $result = $this->getResult();
913 $requestid = $this->getParameter( 'requestid' );
914 if ( !is_null( $requestid ) ) {
915 $result->addValue( null, 'requestid', $requestid );
918 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
919 $servedby = $this->getParameter( 'servedby' );
921 $result->addValue( null, 'servedby', wfHostName() );
925 if ( $this->getParameter( 'curtimestamp' ) ) {
926 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
927 ApiResult
::NO_SIZE_CHECK
);
930 $params = $this->extractRequestParams();
932 $this->mAction
= $params['action'];
934 if ( !is_string( $this->mAction
) ) {
935 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
942 * Set up the module for response
943 * @return ApiBase The module that will handle this action
944 * @throws MWException
945 * @throws UsageException
947 protected function setupModule() {
948 // Instantiate the module requested by the user
949 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
950 if ( $module === null ) {
951 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
953 $moduleParams = $module->extractRequestParams();
955 // Check token, if necessary
956 if ( $module->needsToken() === true ) {
957 throw new MWException(
958 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
959 "See documentation for ApiBase::needsToken for details."
962 if ( $module->needsToken() ) {
963 if ( !$module->mustBePosted() ) {
964 throw new MWException(
965 "Module '{$module->getModuleName()}' must require POST to use tokens."
969 if ( !isset( $moduleParams['token'] ) ) {
970 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
973 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
975 $module->encodeParamName( 'token' ),
976 $this->getRequest()->getQueryValues()
980 "The '{$module->encodeParamName( 'token' )}' parameter was found in the query string, but must be in the POST body",
985 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
986 $this->dieUsageMsg( 'sessionfailure' );
994 * Check the max lag if necessary
995 * @param ApiBase $module Api module being used
996 * @param array $params Array an array containing the request parameters.
997 * @return bool True on success, false should exit immediately
999 protected function checkMaxLag( $module, $params ) {
1000 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
1002 $maxLag = $params['maxlag'];
1003 list( $host, $lag ) = wfGetLB()->getMaxLag();
1004 if ( $lag > $maxLag ) {
1005 $response = $this->getRequest()->response();
1007 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1008 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
1010 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1011 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
1014 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
1022 * Check selected RFC 7232 precondition headers
1024 * RFC 7232 envisions a particular model where you send your request to "a
1025 * resource", and for write requests that you can read "the resource" by
1026 * changing the method to GET. When the API receives a GET request, it
1027 * works out even though "the resource" from RFC 7232's perspective might
1028 * be many resources from MediaWiki's perspective. But it totally fails for
1029 * a POST, since what HTTP sees as "the resource" is probably just
1030 * "/api.php" with all the interesting bits in the body.
1032 * Therefore, we only support RFC 7232 precondition headers for GET (and
1033 * HEAD). That means we don't need to bother with If-Match and
1034 * If-Unmodified-Since since they only apply to modification requests.
1036 * And since we don't support Range, If-Range is ignored too.
1039 * @param ApiBase $module Api module being used
1040 * @return bool True on success, false should exit immediately
1042 protected function checkConditionalRequestHeaders( $module ) {
1043 if ( $this->mInternalMode
) {
1044 // No headers to check in internal mode
1048 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1049 // Don't check POSTs
1055 $ifNoneMatch = array_diff(
1056 $this->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
) ?
: array(),
1059 if ( $ifNoneMatch ) {
1060 if ( $ifNoneMatch === array( '*' ) ) {
1061 // API responses always "exist"
1064 $etag = $module->getConditionalRequestData( 'etag' );
1067 if ( $ifNoneMatch && $etag !== null ) {
1068 $test = substr( $etag, 0, 2 ) === 'W/' ?
substr( $etag, 2 ) : $etag;
1069 $match = array_map( function ( $s ) {
1070 return substr( $s, 0, 2 ) === 'W/' ?
substr( $s, 2 ) : $s;
1072 $return304 = in_array( $test, $match, true );
1074 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1076 // Some old browsers sends sizes after the date, like this:
1077 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1079 $i = strpos( $value, ';' );
1080 if ( $i !== false ) {
1081 $value = trim( substr( $value, 0, $i ) );
1084 if ( $value !== '' ) {
1086 $ts = new MWTimestamp( $value );
1088 // RFC 7231 IMF-fixdate
1089 $ts->getTimestamp( TS_RFC2822
) === $value ||
1091 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1092 // asctime (with and without space-padded day)
1093 $ts->format( 'D M j H:i:s Y' ) === $value ||
1094 $ts->format( 'D M j H:i:s Y' ) === $value
1096 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1097 if ( $lastMod !== null ) {
1098 // Mix in some MediaWiki modification times
1099 $modifiedTimes = array(
1101 'user' => $this->getUser()->getTouched(),
1102 'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1104 if ( $this->getConfig()->get( 'UseSquid' ) ) {
1105 // T46570: the core page itself may not change, but resources might
1106 $modifiedTimes['sepoch'] = wfTimestamp(
1107 TS_MW
, time() - $this->getConfig()->get( 'SquidMaxage' )
1110 Hooks
::run( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
1111 $lastMod = max( $modifiedTimes );
1112 $return304 = wfTimestamp( TS_MW
, $lastMod ) <= $ts->getTimestamp( TS_MW
);
1115 } catch ( TimestampException
$e ) {
1116 // Invalid timestamp, ignore it
1122 $this->getRequest()->response()->statusHeader( 304 );
1124 // Avoid outputting the compressed representation of a zero-length body
1125 MediaWiki\
suppressWarnings();
1126 ini_set( 'zlib.output_compression', 0 );
1127 MediaWiki\restoreWarnings
();
1128 wfClearOutputBuffers();
1137 * Check for sufficient permissions to execute
1138 * @param ApiBase $module An Api module
1140 protected function checkExecutePermissions( $module ) {
1141 $user = $this->getUser();
1142 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
1143 !$user->isAllowed( 'read' )
1145 $this->dieUsageMsg( 'readrequired' );
1147 if ( $module->isWriteMode() ) {
1148 if ( !$this->mEnableWrite
) {
1149 $this->dieUsageMsg( 'writedisabled' );
1151 if ( !$user->isAllowed( 'writeapi' ) ) {
1152 $this->dieUsageMsg( 'writerequired' );
1154 if ( wfReadOnly() ) {
1155 $this->dieReadOnly();
1159 // Allow extensions to stop execution for arbitrary reasons.
1161 if ( !Hooks
::run( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
1162 $this->dieUsageMsg( $message );
1167 * Check asserts of the user's rights
1168 * @param array $params
1170 protected function checkAsserts( $params ) {
1171 if ( isset( $params['assert'] ) ) {
1172 $user = $this->getUser();
1173 switch ( $params['assert'] ) {
1175 if ( $user->isAnon() ) {
1176 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
1180 if ( !$user->isAllowed( 'bot' ) ) {
1181 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1189 * Check POST for external response and setup result printer
1190 * @param ApiBase $module An Api module
1191 * @param array $params An array with the request parameters
1193 protected function setupExternalResponse( $module, $params ) {
1194 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
1195 // Module requires POST. GET request might still be allowed
1196 // if $wgDebugApi is true, otherwise fail.
1197 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction
) );
1200 // See if custom printer is used
1201 $this->mPrinter
= $module->getCustomPrinter();
1202 if ( is_null( $this->mPrinter
) ) {
1203 // Create an appropriate printer
1204 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1209 * Execute the actual module, without any error handling
1211 protected function executeAction() {
1212 $params = $this->setupExecuteAction();
1213 $module = $this->setupModule();
1214 $this->mModule
= $module;
1216 $this->checkExecutePermissions( $module );
1218 if ( !$this->checkMaxLag( $module, $params ) ) {
1222 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1226 if ( !$this->mInternalMode
) {
1227 $this->setupExternalResponse( $module, $params );
1230 $this->checkAsserts( $params );
1234 Hooks
::run( 'APIAfterExecute', array( &$module ) );
1236 $this->reportUnusedParams();
1238 if ( !$this->mInternalMode
) {
1239 //append Debug information
1240 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1242 // Print result data
1243 $this->printResult( false );
1248 * Log the preceding request
1249 * @param int $time Time in seconds
1251 protected function logRequest( $time ) {
1252 $request = $this->getRequest();
1253 $milliseconds = $time === null ?
'?' : round( $time * 1000 );
1255 ' ' . $request->getMethod() .
1256 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1257 ' ' . $request->getIP() .
1258 ' T=' . $milliseconds . 'ms';
1259 foreach ( $this->getParamsUsed() as $name ) {
1260 $value = $request->getVal( $name );
1261 if ( $value === null ) {
1264 $s .= ' ' . $name . '=';
1265 if ( strlen( $value ) > 256 ) {
1266 $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
1267 $s .= $encValue . '[...]';
1269 $s .= $this->encodeRequestLogValue( $value );
1273 wfDebugLog( 'api', $s, 'private' );
1277 * Encode a value in a format suitable for a space-separated log line.
1281 protected function encodeRequestLogValue( $s ) {
1284 $chars = ';@$!*(),/:';
1285 $numChars = strlen( $chars );
1286 for ( $i = 0; $i < $numChars; $i++
) {
1287 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1291 return strtr( rawurlencode( $s ), $table );
1295 * Get the request parameters used in the course of the preceding execute() request
1298 protected function getParamsUsed() {
1299 return array_keys( $this->mParamsUsed
);
1303 * Get a request value, and register the fact that it was used, for logging.
1304 * @param string $name
1305 * @param mixed $default
1308 public function getVal( $name, $default = null ) {
1309 $this->mParamsUsed
[$name] = true;
1311 $ret = $this->getRequest()->getVal( $name );
1312 if ( $ret === null ) {
1313 if ( $this->getRequest()->getArray( $name ) !== null ) {
1314 // See bug 10262 for why we don't just join( '|', ... ) the
1317 "Parameter '$name' uses unsupported PHP array syntax"
1326 * Get a boolean request value, and register the fact that the parameter
1327 * was used, for logging.
1328 * @param string $name
1331 public function getCheck( $name ) {
1332 return $this->getVal( $name, null ) !== null;
1336 * Get a request upload, and register the fact that it was used, for logging.
1339 * @param string $name Parameter name
1340 * @return WebRequestUpload
1342 public function getUpload( $name ) {
1343 $this->mParamsUsed
[$name] = true;
1345 return $this->getRequest()->getUpload( $name );
1349 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1350 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1352 protected function reportUnusedParams() {
1353 $paramsUsed = $this->getParamsUsed();
1354 $allParams = $this->getRequest()->getValueNames();
1356 if ( !$this->mInternalMode
) {
1357 // Printer has not yet executed; don't warn that its parameters are unused
1358 $printerParams = array_map(
1359 array( $this->mPrinter
, 'encodeParamName' ),
1360 array_keys( $this->mPrinter
->getFinalParams() ?
: array() )
1362 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1364 $unusedParams = array_diff( $allParams, $paramsUsed );
1367 if ( count( $unusedParams ) ) {
1368 $s = count( $unusedParams ) > 1 ?
's' : '';
1369 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1374 * Print results using the current printer
1376 * @param bool $isError
1378 protected function printResult( $isError ) {
1379 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1380 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1383 $printer = $this->mPrinter
;
1384 $printer->initPrinter( false );
1385 $printer->execute();
1386 $printer->closePrinter();
1392 public function isReadMode() {
1397 * See ApiBase for description.
1401 public function getAllowedParams() {
1404 ApiBase
::PARAM_DFLT
=> 'help',
1405 ApiBase
::PARAM_TYPE
=> 'submodule',
1408 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1409 ApiBase
::PARAM_TYPE
=> 'submodule',
1412 ApiBase
::PARAM_TYPE
=> 'integer'
1415 ApiBase
::PARAM_TYPE
=> 'integer',
1416 ApiBase
::PARAM_DFLT
=> 0
1419 ApiBase
::PARAM_TYPE
=> 'integer',
1420 ApiBase
::PARAM_DFLT
=> 0
1423 ApiBase
::PARAM_TYPE
=> array( 'user', 'bot' )
1425 'requestid' => null,
1426 'servedby' => false,
1427 'curtimestamp' => false,
1430 ApiBase
::PARAM_DFLT
=> 'user',
1435 /** @see ApiBase::getExamplesMessages() */
1436 protected function getExamplesMessages() {
1439 => 'apihelp-help-example-main',
1440 'action=help&recursivesubmodules=1'
1441 => 'apihelp-help-example-recursive',
1445 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1446 // Wish PHP had an "array_insert_before". Instead, we have to manually
1447 // reindex the array to get 'permissions' in the right place.
1450 foreach ( $oldHelp as $k => $v ) {
1451 if ( $k === 'submodules' ) {
1452 $help['permissions'] = '';
1456 $help['datatypes'] = '';
1457 $help['credits'] = '';
1459 // Fill 'permissions'
1460 $help['permissions'] .= Html
::openElement( 'div',
1461 array( 'class' => 'apihelp-block apihelp-permissions' ) );
1462 $m = $this->msg( 'api-help-permissions' );
1463 if ( !$m->isDisabled() ) {
1464 $help['permissions'] .= Html
::rawElement( 'div', array( 'class' => 'apihelp-block-head' ),
1465 $m->numParams( count( self
::$mRights ) )->parse()
1468 $help['permissions'] .= Html
::openElement( 'dl' );
1469 foreach ( self
::$mRights as $right => $rightMsg ) {
1470 $help['permissions'] .= Html
::element( 'dt', null, $right );
1472 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1473 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1475 $groups = array_map( function ( $group ) {
1476 return $group == '*' ?
'all' : $group;
1477 }, User
::getGroupsWithPermission( $right ) );
1479 $help['permissions'] .= Html
::rawElement( 'dd', null,
1480 $this->msg( 'api-help-permissions-granted-to' )
1481 ->numParams( count( $groups ) )
1482 ->params( $this->getLanguage()->commaList( $groups ) )
1486 $help['permissions'] .= Html
::closeElement( 'dl' );
1487 $help['permissions'] .= Html
::closeElement( 'div' );
1489 // Fill 'datatypes' and 'credits', if applicable
1490 if ( empty( $options['nolead'] ) ) {
1491 $level = $options['headerlevel'];
1492 $tocnumber = &$options['tocnumber'];
1494 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1495 $help['datatypes'] .= Html
::rawelement( 'h' . min( 6, $level ),
1496 array( 'id' => 'main/datatypes', 'class' => 'apihelp-header' ),
1497 Html
::element( 'span', array( 'id' => Sanitizer
::escapeId( 'main/datatypes' ) ) ) .
1500 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1501 if ( !isset( $tocData['main/datatypes'] ) ) {
1502 $tocnumber[$level]++
;
1503 $tocData['main/datatypes'] = array(
1504 'toclevel' => count( $tocnumber ),
1506 'anchor' => 'main/datatypes',
1508 'number' => join( '.', $tocnumber ),
1513 $header = $this->msg( 'api-credits-header' )->parse();
1514 $help['credits'] .= Html
::rawelement( 'h' . min( 6, $level ),
1515 array( 'id' => 'main/credits', 'class' => 'apihelp-header' ),
1516 Html
::element( 'span', array( 'id' => Sanitizer
::escapeId( 'main/credits' ) ) ) .
1519 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1520 if ( !isset( $tocData['main/credits'] ) ) {
1521 $tocnumber[$level]++
;
1522 $tocData['main/credits'] = array(
1523 'toclevel' => count( $tocnumber ),
1525 'anchor' => 'main/credits',
1527 'number' => join( '.', $tocnumber ),
1534 private $mCanApiHighLimits = null;
1537 * Check whether the current user is allowed to use high limits
1540 public function canApiHighLimits() {
1541 if ( !isset( $this->mCanApiHighLimits
) ) {
1542 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1545 return $this->mCanApiHighLimits
;
1549 * Overrides to return this instance's module manager.
1550 * @return ApiModuleManager
1552 public function getModuleManager() {
1553 return $this->mModuleMgr
;
1557 * Fetches the user agent used for this request
1559 * The value will be the combination of the 'Api-User-Agent' header (if
1560 * any) and the standard User-Agent header (if any).
1564 public function getUserAgent() {
1566 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1567 $this->getRequest()->getHeader( 'User-agent' )
1571 /************************************************************************//**
1577 * Sets whether the pretty-printer should format *bold* and $italics$
1579 * @deprecated since 1.25
1582 public function setHelp( $help = true ) {
1583 wfDeprecated( __METHOD__
, '1.25' );
1584 $this->mPrinter
->setHelp( $help );
1588 * Override the parent to generate help messages for all available modules.
1590 * @deprecated since 1.25
1593 public function makeHelpMsg() {
1594 wfDeprecated( __METHOD__
, '1.25' );
1597 // Get help text from cache if present
1598 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1599 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) ) );
1601 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1602 if ( $cacheHelpTimeout > 0 ) {
1603 $cached = $wgMemc->get( $key );
1608 $retval = $this->reallyMakeHelpMsg();
1609 if ( $cacheHelpTimeout > 0 ) {
1610 $wgMemc->set( $key, $retval, $cacheHelpTimeout );
1617 * @deprecated since 1.25
1618 * @return mixed|string
1620 public function reallyMakeHelpMsg() {
1621 wfDeprecated( __METHOD__
, '1.25' );
1624 // Use parent to make default message for the main module
1625 $msg = parent
::makeHelpMsg();
1627 $astriks = str_repeat( '*** ', 14 );
1628 $msg .= "\n\n$astriks Modules $astriks\n\n";
1630 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1631 $module = $this->mModuleMgr
->getModule( $name );
1632 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1634 $msg2 = $module->makeHelpMsg();
1635 if ( $msg2 !== false ) {
1641 $msg .= "\n$astriks Permissions $astriks\n\n";
1642 foreach ( self
::$mRights as $right => $rightMsg ) {
1643 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1644 ->useDatabase( false )
1645 ->inLanguage( 'en' )
1647 $groups = User
::getGroupsWithPermission( $right );
1648 $msg .= "* " . $right . " *\n $rightsMsg" .
1649 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1652 $msg .= "\n$astriks Formats $astriks\n\n";
1653 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1654 $module = $this->mModuleMgr
->getModule( $name );
1655 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1656 $msg2 = $module->makeHelpMsg();
1657 if ( $msg2 !== false ) {
1663 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1664 $credits = str_replace( "\n", "\n ", $credits );
1665 $msg .= "\n*** Credits: ***\n $credits\n";
1671 * @deprecated since 1.25
1672 * @param ApiBase $module
1673 * @param string $paramName What type of request is this? e.g. action,
1674 * query, list, prop, meta, format
1677 public static function makeHelpMsgHeader( $module, $paramName ) {
1678 wfDeprecated( __METHOD__
, '1.25' );
1679 $modulePrefix = $module->getModulePrefix();
1680 if ( strval( $modulePrefix ) !== '' ) {
1681 $modulePrefix = "($modulePrefix) ";
1684 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1688 * Check whether the user wants us to show version information in the API help
1690 * @deprecated since 1.21, always returns false
1692 public function getShowVersions() {
1693 wfDeprecated( __METHOD__
, '1.21' );
1699 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1700 * classes who wish to add their own modules to their lexicon or override the
1701 * behavior of inherent ones.
1703 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1704 * @param string $name The identifier for this module.
1705 * @param ApiBase $class The class where this module is implemented.
1707 protected function addModule( $name, $class ) {
1708 $this->getModuleManager()->addModule( $name, 'action', $class );
1712 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1713 * classes who wish to add to or modify current formatters.
1715 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1716 * @param string $name The identifier for this format.
1717 * @param ApiFormatBase $class The class implementing this format.
1719 protected function addFormat( $name, $class ) {
1720 $this->getModuleManager()->addModule( $name, 'format', $class );
1724 * Get the array mapping module names to class names
1725 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1728 function getModules() {
1729 return $this->getModuleManager()->getNamesWithClasses( 'action' );
1733 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1736 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1739 public function getFormats() {
1740 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1748 * This exception will be thrown when dieUsage is called to stop module execution.
1752 class UsageException
extends MWException
{
1759 private $mExtraData;
1762 * @param string $message
1763 * @param string $codestr
1765 * @param array|null $extradata
1767 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1768 parent
::__construct( $message, $code );
1769 $this->mCodestr
= $codestr;
1770 $this->mExtraData
= $extradata;
1776 public function getCodeString() {
1777 return $this->mCodestr
;
1783 public function getMessageArray() {
1785 'code' => $this->mCodestr
,
1786 'info' => $this->getMessage()
1788 if ( is_array( $this->mExtraData
) ) {
1789 $result = array_merge( $result, $this->mExtraData
);
1798 public function __toString() {
1799 return "{$this->getCodeString()}: {$this->getMessage()}";
1804 * For really cool vim folding this needs to be at the end:
1805 * vim: foldmarker=@{,@} foldmethod=marker