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 'rawfm' => 'ApiFormatJson',
106 'none' => 'ApiFormatNone',
109 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
111 * List of user roles that are specifically relevant to the API.
112 * array( 'right' => array ( 'msg' => 'Some message with a $1',
113 * 'params' => array ( $someVarToSubst ) ),
116 private static $mRights = array(
118 'msg' => 'right-writeapi',
121 'apihighlimits' => array(
122 'msg' => 'api-help-right-apihighlimits',
123 'params' => array( ApiBase
::LIMIT_SML2
, ApiBase
::LIMIT_BIG2
)
126 // @codingStandardsIgnoreEnd
133 private $mModuleMgr, $mResult, $mErrorFormatter, $mContinuationManager;
135 private $mEnableWrite;
136 private $mInternalMode, $mSquidMaxage, $mModule;
138 private $mCacheMode = 'private';
139 private $mCacheControl = array();
140 private $mParamsUsed = array();
143 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
145 * @param IContextSource|WebRequest $context If this is an instance of
146 * FauxRequest, errors are thrown and no printing occurs
147 * @param bool $enableWrite Should be set to true if the api may modify data
149 public function __construct( $context = null, $enableWrite = false ) {
150 if ( $context === null ) {
151 $context = RequestContext
::getMain();
152 } elseif ( $context instanceof WebRequest
) {
155 $context = RequestContext
::getMain();
157 // We set a derivative context so we can change stuff later
158 $this->setContext( new DerivativeContext( $context ) );
160 if ( isset( $request ) ) {
161 $this->getContext()->setRequest( $request );
164 $this->mInternalMode
= ( $this->getRequest() instanceof FauxRequest
);
166 // Special handling for the main module: $parent === $this
167 parent
::__construct( $this, $this->mInternalMode ?
'main_int' : 'main' );
169 if ( !$this->mInternalMode
) {
170 // Impose module restrictions.
171 // If the current user cannot read,
172 // Remove all modules other than login
175 if ( $this->lacksSameOriginSecurity() ) {
176 // If we're in a mode that breaks the same-origin policy, strip
177 // user credentials for security.
178 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
179 $wgUser = new User();
180 $this->getContext()->setUser( $wgUser );
184 $uselang = $this->getParameter( 'uselang' );
185 if ( $uselang === 'user' ) {
186 // Assume the parent context is going to return the user language
187 // for uselang=user (see T85635).
189 if ( $uselang === 'content' ) {
191 $uselang = $wgContLang->getCode();
193 $code = RequestContext
::sanitizeLangCode( $uselang );
194 $this->getContext()->setLanguage( $code );
195 if ( !$this->mInternalMode
) {
197 $wgLang = $this->getContext()->getLanguage();
198 RequestContext
::getMain()->setLanguage( $wgLang );
202 $config = $this->getConfig();
203 $this->mModuleMgr
= new ApiModuleManager( $this );
204 $this->mModuleMgr
->addModules( self
::$Modules, 'action' );
205 $this->mModuleMgr
->addModules( $config->get( 'APIModules' ), 'action' );
206 $this->mModuleMgr
->addModules( self
::$Formats, 'format' );
207 $this->mModuleMgr
->addModules( $config->get( 'APIFormatModules' ), 'format' );
209 Hooks
::run( 'ApiMain::moduleManager', array( $this->mModuleMgr
) );
211 $this->mResult
= new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) );
212 $this->mErrorFormatter
= new ApiErrorFormatter_BackCompat( $this->mResult
);
213 $this->mResult
->setErrorFormatter( $this->mErrorFormatter
);
214 $this->mResult
->setMainForContinuation( $this );
215 $this->mContinuationManager
= null;
216 $this->mEnableWrite
= $enableWrite;
218 $this->mSquidMaxage
= -1; // flag for executeActionWithErrorHandling()
219 $this->mCommit
= false;
223 * Return true if the API was started by other PHP code using FauxRequest
226 public function isInternalMode() {
227 return $this->mInternalMode
;
231 * Get the ApiResult object associated with current request
235 public function getResult() {
236 return $this->mResult
;
240 * Get the ApiErrorFormatter object associated with current request
241 * @return ApiErrorFormatter
243 public function getErrorFormatter() {
244 return $this->mErrorFormatter
;
248 * Get the continuation manager
249 * @return ApiContinuationManager|null
251 public function getContinuationManager() {
252 return $this->mContinuationManager
;
256 * Set the continuation manager
257 * @param ApiContinuationManager|null
259 public function setContinuationManager( $manager ) {
260 if ( $manager !== null ) {
261 if ( !$manager instanceof ApiContinuationManager
) {
262 throw new InvalidArgumentException( __METHOD__
. ': Was passed ' .
263 is_object( $manager ) ?
get_class( $manager ) : gettype( $manager )
266 if ( $this->mContinuationManager
!== null ) {
267 throw new UnexpectedValueException(
268 __METHOD__
. ': tried to set manager from ' . $manager->getSource() .
269 ' when a manager is already set from ' . $this->mContinuationManager
->getSource()
273 $this->mContinuationManager
= $manager;
277 * Get the API module object. Only works after executeAction()
281 public function getModule() {
282 return $this->mModule
;
286 * Get the result formatter object. Only works after setupExecuteAction()
288 * @return ApiFormatBase
290 public function getPrinter() {
291 return $this->mPrinter
;
295 * Set how long the response should be cached.
299 public function setCacheMaxAge( $maxage ) {
300 $this->setCacheControl( array(
301 'max-age' => $maxage,
302 's-maxage' => $maxage
307 * Set the type of caching headers which will be sent.
309 * @param string $mode One of:
310 * - 'public': Cache this object in public caches, if the maxage or smaxage
311 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
312 * not provided by any of these means, the object will be private.
313 * - 'private': Cache this object only in private client-side caches.
314 * - 'anon-public-user-private': Make this object cacheable for logged-out
315 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
316 * set consistently for a given URL, it cannot be set differently depending on
317 * things like the contents of the database, or whether the user is logged in.
319 * If the wiki does not allow anonymous users to read it, the mode set here
320 * will be ignored, and private caching headers will always be sent. In other words,
321 * the "public" mode is equivalent to saying that the data sent is as public as a page
324 * For user-dependent data, the private mode should generally be used. The
325 * anon-public-user-private mode should only be used where there is a particularly
326 * good performance reason for caching the anonymous response, but where the
327 * response to logged-in users may differ, or may contain private data.
329 * If this function is never called, then the default will be the private mode.
331 public function setCacheMode( $mode ) {
332 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
333 wfDebug( __METHOD__
. ": unrecognised cache mode \"$mode\"\n" );
335 // Ignore for forwards-compatibility
339 if ( !User
::isEveryoneAllowed( 'read' ) ) {
340 // Private wiki, only private headers
341 if ( $mode !== 'private' ) {
342 wfDebug( __METHOD__
. ": ignoring request for $mode cache mode, private wiki\n" );
348 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
349 // User language is used for i18n, so we don't want to publicly
350 // cache. Anons are ok, because if they have non-default language
351 // then there's an appropriate Vary header set by whatever set
352 // their non-default language.
353 wfDebug( __METHOD__
. ": downgrading cache mode 'public' to " .
354 "'anon-public-user-private' due to uselang=user\n" );
355 $mode = 'anon-public-user-private';
358 wfDebug( __METHOD__
. ": setting cache mode $mode\n" );
359 $this->mCacheMode
= $mode;
363 * Set directives (key/value pairs) for the Cache-Control header.
364 * Boolean values will be formatted as such, by including or omitting
365 * without an equals sign.
367 * Cache control values set here will only be used if the cache mode is not
368 * private, see setCacheMode().
370 * @param array $directives
372 public function setCacheControl( $directives ) {
373 $this->mCacheControl
= $directives +
$this->mCacheControl
;
377 * Create an instance of an output formatter by its name
379 * @param string $format
381 * @return ApiFormatBase
383 public function createPrinterByName( $format ) {
384 $printer = $this->mModuleMgr
->getModule( $format, 'format' );
385 if ( $printer === null ) {
386 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
393 * Execute api request. Any errors will be handled if the API was called by the remote client.
395 public function execute() {
396 if ( $this->mInternalMode
) {
397 $this->executeAction();
399 $this->executeActionWithErrorHandling();
404 * Execute an action, and in case of an error, erase whatever partial results
405 * have been accumulated, and replace it with an error message and a help screen.
407 protected function executeActionWithErrorHandling() {
408 // Verify the CORS header before executing the action
409 if ( !$this->handleCORS() ) {
410 // handleCORS() has sent a 403, abort
414 // Exit here if the request method was OPTIONS
415 // (assume there will be a followup GET or POST)
416 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
420 // In case an error occurs during data output,
421 // clear the output buffer and print just the error information
422 $obLevel = ob_get_level();
425 $t = microtime( true );
427 $this->executeAction();
429 } catch ( Exception
$e ) {
430 $this->handleException( $e );
434 // Log the request whether or not there was an error
435 $this->logRequest( microtime( true ) - $t );
437 // Send cache headers after any code which might generate an error, to
438 // avoid sending public cache headers for errors.
439 $this->sendCacheHeaders( $isError );
441 // Executing the action might have already messed with the output
443 while ( ob_get_level() > $obLevel ) {
449 * Handle an exception as an API response
452 * @param Exception $e
454 protected function handleException( Exception
$e ) {
455 // Bug 63145: Rollback any open database transactions
456 if ( !( $e instanceof UsageException
) ) {
457 // UsageExceptions are intentional, so don't rollback if that's the case
459 MWExceptionHandler
::rollbackMasterChangesAndLog( $e );
460 } catch ( DBError
$e2 ) {
461 // Rollback threw an exception too. Log it, but don't interrupt
462 // our regularly scheduled exception handling.
463 MWExceptionHandler
::logException( $e2 );
467 // Allow extra cleanup and logging
468 Hooks
::run( 'ApiMain::onException', array( $this, $e ) );
471 if ( !( $e instanceof UsageException
) ) {
472 MWExceptionHandler
::logException( $e );
475 // Handle any kind of exception by outputting properly formatted error message.
476 // If this fails, an unhandled exception should be thrown so that global error
477 // handler will process and log it.
479 $errCode = $this->substituteResultWithError( $e );
481 // Error results should not be cached
482 $this->setCacheMode( 'private' );
484 $response = $this->getRequest()->response();
485 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
486 if ( $e->getCode() === 0 ) {
487 $response->header( $headerStr );
489 $response->header( $headerStr, true, $e->getCode() );
492 // Reset and print just the error message
495 // Printer may not be initialized if the extractRequestParams() fails for the main module
496 $this->createErrorPrinter();
499 $this->printResult( true );
500 } catch ( UsageException
$ex ) {
501 // The error printer itself is failing. Try suppressing its request
502 // parameters and redo.
504 'Error printer failed (will retry without params): ' . $ex->getMessage()
506 $this->mPrinter
= null;
507 $this->createErrorPrinter();
508 $this->mPrinter
->forceDefaultParams();
509 $this->printResult( true );
514 * Handle an exception from the ApiBeforeMain hook.
516 * This tries to print the exception as an API response, to be more
517 * friendly to clients. If it fails, it will rethrow the exception.
520 * @param Exception $e
523 public static function handleApiBeforeMainException( Exception
$e ) {
527 $main = new self( RequestContext
::getMain(), false );
528 $main->handleException( $e );
529 } catch ( Exception
$e2 ) {
530 // Nope, even that didn't work. Punt.
534 // Log the request and reset cache headers
535 $main->logRequest( 0 );
536 $main->sendCacheHeaders( true );
542 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
544 * If no origin parameter is present, nothing happens.
545 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
546 * is set and false is returned.
547 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
548 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
550 * http://www.w3.org/TR/cors/#resource-requests
551 * http://www.w3.org/TR/cors/#resource-preflight-requests
553 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
555 protected function handleCORS() {
556 $originParam = $this->getParameter( 'origin' ); // defaults to null
557 if ( $originParam === null ) {
558 // No origin parameter, nothing to do
562 $request = $this->getRequest();
563 $response = $request->response();
565 // Origin: header is a space-separated list of origins, check all of them
566 $originHeader = $request->getHeader( 'Origin' );
567 if ( $originHeader === false ) {
570 $originHeader = trim( $originHeader );
571 $origins = preg_split( '/\s+/', $originHeader );
574 if ( !in_array( $originParam, $origins ) ) {
575 // origin parameter set but incorrect
576 // Send a 403 response
577 $response->statusHeader( 403 );
578 $response->header( 'Cache-Control: no-cache' );
579 echo "'origin' parameter does not match Origin header\n";
584 $config = $this->getConfig();
585 $matchOrigin = count( $origins ) === 1 && self
::matchOrigin(
587 $config->get( 'CrossSiteAJAXdomains' ),
588 $config->get( 'CrossSiteAJAXdomainExceptions' )
591 if ( $matchOrigin ) {
592 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
593 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
595 // This is a CORS preflight request
596 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
597 // If method is not a case-sensitive match, do not set any additional headers and terminate.
600 // We allow the actual request to send the following headers
601 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
602 if ( $requestedHeaders !== false ) {
603 if ( !self
::matchRequestedHeaders( $requestedHeaders ) ) {
606 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
609 // We only allow the actual request to be GET or POST
610 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
613 $response->header( "Access-Control-Allow-Origin: $originHeader" );
614 $response->header( 'Access-Control-Allow-Credentials: true' );
615 // http://www.w3.org/TR/resource-timing/#timing-allow-origin
616 $response->header( "Timing-Allow-Origin: $originHeader" );
620 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag'
625 $this->getOutput()->addVaryHeader( 'Origin' );
630 * Attempt to match an Origin header against a set of rules and a set of exceptions
631 * @param string $value Origin header
632 * @param array $rules Set of wildcard rules
633 * @param array $exceptions Set of wildcard rules
634 * @return bool True if $value matches a rule in $rules and doesn't match
635 * any rules in $exceptions, false otherwise
637 protected static function matchOrigin( $value, $rules, $exceptions ) {
638 foreach ( $rules as $rule ) {
639 if ( preg_match( self
::wildcardToRegex( $rule ), $value ) ) {
640 // Rule matches, check exceptions
641 foreach ( $exceptions as $exc ) {
642 if ( preg_match( self
::wildcardToRegex( $exc ), $value ) ) {
655 * Attempt to validate the value of Access-Control-Request-Headers against a list
656 * of headers that we allow the follow up request to send.
658 * @param string $requestedHeaders Comma seperated list of HTTP headers
659 * @return bool True if all requested headers are in the list of allowed headers
661 protected static function matchRequestedHeaders( $requestedHeaders ) {
662 if ( trim( $requestedHeaders ) === '' ) {
665 $requestedHeaders = explode( ',', $requestedHeaders );
666 $allowedAuthorHeaders = array_flip( array(
667 /* simple headers (see spec) */
672 /* non-authorable headers in XHR, which are however requested by some UAs */
676 /* MediaWiki whitelist */
679 foreach ( $requestedHeaders as $rHeader ) {
680 $rHeader = strtolower( trim( $rHeader ) );
681 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
682 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
690 * Helper function to convert wildcard string into a regex
694 * @param string $wildcard String with wildcards
695 * @return string Regular expression
697 protected static function wildcardToRegex( $wildcard ) {
698 $wildcard = preg_quote( $wildcard, '/' );
699 $wildcard = str_replace(
705 return "/^https?:\/\/$wildcard$/";
709 * Send caching headers
710 * @param boolean $isError Whether an error response is being output
711 * @since 1.26 added $isError parameter
713 protected function sendCacheHeaders( $isError ) {
714 $response = $this->getRequest()->response();
715 $out = $this->getOutput();
717 $config = $this->getConfig();
719 if ( $config->get( 'VaryOnXFP' ) ) {
720 $out->addVaryHeader( 'X-Forwarded-Proto' );
723 if ( !$isError && $this->mModule
&&
724 ( $this->getRequest()->getMethod() === 'GET' ||
$this->getRequest()->getMethod() === 'HEAD' )
726 $etag = $this->mModule
->getConditionalRequestData( 'etag' );
727 if ( $etag !== null ) {
728 $response->header( "ETag: $etag" );
730 $lastMod = $this->mModule
->getConditionalRequestData( 'last-modified' );
731 if ( $lastMod !== null ) {
732 $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822
, $lastMod ) );
736 // The logic should be:
737 // $this->mCacheControl['max-age'] is set?
738 // Use it, the module knows better than our guess.
739 // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private?
740 // Use 0 because we can guess caching is probably the wrong thing to do.
741 // Use $this->getParameter( 'maxage' ), which already defaults to 0.
743 if ( isset( $this->mCacheControl
['max-age'] ) ) {
744 $maxage = $this->mCacheControl
['max-age'];
745 } elseif ( ( $this->mModule
&& !$this->mModule
->isWriteMode() ) ||
746 $this->mCacheMode
!== 'private'
748 $maxage = $this->getParameter( 'maxage' );
750 $privateCache = 'private, must-revalidate, max-age=' . $maxage;
752 if ( $this->mCacheMode
== 'private' ) {
753 $response->header( "Cache-Control: $privateCache" );
757 $useKeyHeader = $config->get( 'UseKeyHeader' );
758 if ( $this->mCacheMode
== 'anon-public-user-private' ) {
759 $out->addVaryHeader( 'Cookie' );
760 $response->header( $out->getVaryHeader() );
761 if ( $useKeyHeader ) {
762 $response->header( $out->getKeyHeader() );
763 if ( $out->haveCacheVaryCookies() ) {
764 // Logged in, mark this request private
765 $response->header( "Cache-Control: $privateCache" );
768 // Logged out, send normal public headers below
769 } elseif ( session_id() != '' ) {
770 // Logged in or otherwise has session (e.g. anonymous users who have edited)
771 // Mark request private
772 $response->header( "Cache-Control: $privateCache" );
775 } // else no Key and anonymous, send public headers below
778 // Send public headers
779 $response->header( $out->getVaryHeader() );
780 if ( $useKeyHeader ) {
781 $response->header( $out->getKeyHeader() );
784 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
785 if ( !isset( $this->mCacheControl
['s-maxage'] ) ) {
786 $this->mCacheControl
['s-maxage'] = $this->getParameter( 'smaxage' );
788 if ( !isset( $this->mCacheControl
['max-age'] ) ) {
789 $this->mCacheControl
['max-age'] = $this->getParameter( 'maxage' );
792 if ( !$this->mCacheControl
['s-maxage'] && !$this->mCacheControl
['max-age'] ) {
793 // Public cache not requested
794 // Sending a Vary header in this case is harmless, and protects us
795 // against conditional calls of setCacheMaxAge().
796 $response->header( "Cache-Control: $privateCache" );
801 $this->mCacheControl
['public'] = true;
803 // Send an Expires header
804 $maxAge = min( $this->mCacheControl
['s-maxage'], $this->mCacheControl
['max-age'] );
805 $expiryUnixTime = ( $maxAge == 0 ?
1 : time() +
$maxAge );
806 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822
, $expiryUnixTime ) );
808 // Construct the Cache-Control header
811 foreach ( $this->mCacheControl
as $name => $value ) {
812 if ( is_bool( $value ) ) {
814 $ccHeader .= $separator . $name;
818 $ccHeader .= $separator . "$name=$value";
823 $response->header( "Cache-Control: $ccHeader" );
827 * Create the printer for error output
829 private function createErrorPrinter() {
830 if ( !isset( $this->mPrinter
) ) {
831 $value = $this->getRequest()->getVal( 'format', self
::API_DEFAULT_FORMAT
);
832 if ( !$this->mModuleMgr
->isDefined( $value, 'format' ) ) {
833 $value = self
::API_DEFAULT_FORMAT
;
835 $this->mPrinter
= $this->createPrinterByName( $value );
838 // Printer may not be able to handle errors. This is particularly
839 // likely if the module returns something for getCustomPrinter().
840 if ( !$this->mPrinter
->canPrintErrors() ) {
841 $this->mPrinter
= $this->createPrinterByName( self
::API_DEFAULT_FORMAT
);
846 * Replace the result data with the information about an exception.
847 * Returns the error code
848 * @param Exception $e
851 protected function substituteResultWithError( $e ) {
852 $result = $this->getResult();
853 $config = $this->getConfig();
855 if ( $e instanceof UsageException
) {
856 // User entered incorrect parameters - generate error response
857 $errMessage = $e->getMessageArray();
858 $link = wfExpandUrl( wfScript( 'api' ) );
859 ApiResult
::setContentValue( $errMessage, 'docref', "See $link for API usage" );
861 // Something is seriously wrong
862 if ( ( $e instanceof DBQueryError
) && !$config->get( 'ShowSQLErrors' ) ) {
863 $info = 'Database query error';
865 $info = "Exception Caught: {$e->getMessage()}";
869 'code' => 'internal_api_error_' . get_class( $e ),
870 'info' => '[' . MWExceptionHandler
::getLogId( $e ) . '] ' . $info,
872 if ( $config->get( 'ShowExceptionDetails' ) ) {
873 ApiResult
::setContentValue(
876 MWExceptionHandler
::getRedactedTraceAsString( $e )
881 // Remember all the warnings to re-add them later
882 $warnings = $result->getResultData( array( 'warnings' ) );
886 $requestid = $this->getParameter( 'requestid' );
887 if ( !is_null( $requestid ) ) {
888 $result->addValue( null, 'requestid', $requestid, ApiResult
::NO_SIZE_CHECK
);
890 if ( $config->get( 'ShowHostnames' ) ) {
891 // servedby is especially useful when debugging errors
892 $result->addValue( null, 'servedby', wfHostname(), ApiResult
::NO_SIZE_CHECK
);
894 if ( $warnings !== null ) {
895 $result->addValue( null, 'warnings', $warnings, ApiResult
::NO_SIZE_CHECK
);
898 $result->addValue( null, 'error', $errMessage, ApiResult
::NO_SIZE_CHECK
);
900 return $errMessage['code'];
904 * Set up for the execution.
907 protected function setupExecuteAction() {
908 // First add the id to the top element
909 $result = $this->getResult();
910 $requestid = $this->getParameter( 'requestid' );
911 if ( !is_null( $requestid ) ) {
912 $result->addValue( null, 'requestid', $requestid );
915 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
916 $servedby = $this->getParameter( 'servedby' );
918 $result->addValue( null, 'servedby', wfHostName() );
922 if ( $this->getParameter( 'curtimestamp' ) ) {
923 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601
, time() ),
924 ApiResult
::NO_SIZE_CHECK
);
927 $params = $this->extractRequestParams();
929 $this->mAction
= $params['action'];
931 if ( !is_string( $this->mAction
) ) {
932 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
939 * Set up the module for response
940 * @return ApiBase The module that will handle this action
941 * @throws MWException
942 * @throws UsageException
944 protected function setupModule() {
945 // Instantiate the module requested by the user
946 $module = $this->mModuleMgr
->getModule( $this->mAction
, 'action' );
947 if ( $module === null ) {
948 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
950 $moduleParams = $module->extractRequestParams();
952 // Check token, if necessary
953 if ( $module->needsToken() === true ) {
954 throw new MWException(
955 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
956 "See documentation for ApiBase::needsToken for details."
959 if ( $module->needsToken() ) {
960 if ( !$module->mustBePosted() ) {
961 throw new MWException(
962 "Module '{$module->getModuleName()}' must require POST to use tokens."
966 if ( !isset( $moduleParams['token'] ) ) {
967 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
970 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
972 $module->encodeParamName( 'token' ),
973 $this->getRequest()->getQueryValues()
977 "The '{$module->encodeParamName( 'token' )}' parameter was " .
978 'found in the query string, but must be in the POST body',
983 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
984 $this->dieUsageMsg( 'sessionfailure' );
992 * Check the max lag if necessary
993 * @param ApiBase $module Api module being used
994 * @param array $params Array an array containing the request parameters.
995 * @return bool True on success, false should exit immediately
997 protected function checkMaxLag( $module, $params ) {
998 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
999 $maxLag = $params['maxlag'];
1000 list( $host, $lag ) = wfGetLB()->getMaxLag();
1001 if ( $lag > $maxLag ) {
1002 $response = $this->getRequest()->response();
1004 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
1005 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
1007 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
1008 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
1011 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
1019 * Check selected RFC 7232 precondition headers
1021 * RFC 7232 envisions a particular model where you send your request to "a
1022 * resource", and for write requests that you can read "the resource" by
1023 * changing the method to GET. When the API receives a GET request, it
1024 * works out even though "the resource" from RFC 7232's perspective might
1025 * be many resources from MediaWiki's perspective. But it totally fails for
1026 * a POST, since what HTTP sees as "the resource" is probably just
1027 * "/api.php" with all the interesting bits in the body.
1029 * Therefore, we only support RFC 7232 precondition headers for GET (and
1030 * HEAD). That means we don't need to bother with If-Match and
1031 * If-Unmodified-Since since they only apply to modification requests.
1033 * And since we don't support Range, If-Range is ignored too.
1036 * @param ApiBase $module Api module being used
1037 * @return bool True on success, false should exit immediately
1039 protected function checkConditionalRequestHeaders( $module ) {
1040 if ( $this->mInternalMode
) {
1041 // No headers to check in internal mode
1045 if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) {
1046 // Don't check POSTs
1052 $ifNoneMatch = array_diff(
1053 $this->getRequest()->getHeader( 'If-None-Match', WebRequest
::GETHEADER_LIST
) ?
: array(),
1056 if ( $ifNoneMatch ) {
1057 if ( $ifNoneMatch === array( '*' ) ) {
1058 // API responses always "exist"
1061 $etag = $module->getConditionalRequestData( 'etag' );
1064 if ( $ifNoneMatch && $etag !== null ) {
1065 $test = substr( $etag, 0, 2 ) === 'W/' ?
substr( $etag, 2 ) : $etag;
1066 $match = array_map( function ( $s ) {
1067 return substr( $s, 0, 2 ) === 'W/' ?
substr( $s, 2 ) : $s;
1069 $return304 = in_array( $test, $match, true );
1071 $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) );
1073 // Some old browsers sends sizes after the date, like this:
1074 // Wed, 20 Aug 2003 06:51:19 GMT; length=5202
1076 $i = strpos( $value, ';' );
1077 if ( $i !== false ) {
1078 $value = trim( substr( $value, 0, $i ) );
1081 if ( $value !== '' ) {
1083 $ts = new MWTimestamp( $value );
1085 // RFC 7231 IMF-fixdate
1086 $ts->getTimestamp( TS_RFC2822
) === $value ||
1088 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value ||
1089 // asctime (with and without space-padded day)
1090 $ts->format( 'D M j H:i:s Y' ) === $value ||
1091 $ts->format( 'D M j H:i:s Y' ) === $value
1093 $lastMod = $module->getConditionalRequestData( 'last-modified' );
1094 if ( $lastMod !== null ) {
1095 // Mix in some MediaWiki modification times
1096 $modifiedTimes = array(
1098 'user' => $this->getUser()->getTouched(),
1099 'epoch' => $this->getConfig()->get( 'CacheEpoch' ),
1101 if ( $this->getConfig()->get( 'UseSquid' ) ) {
1102 // T46570: the core page itself may not change, but resources might
1103 $modifiedTimes['sepoch'] = wfTimestamp(
1104 TS_MW
, time() - $this->getConfig()->get( 'SquidMaxage' )
1107 Hooks
::run( 'OutputPageCheckLastModified', array( &$modifiedTimes ) );
1108 $lastMod = max( $modifiedTimes );
1109 $return304 = wfTimestamp( TS_MW
, $lastMod ) <= $ts->getTimestamp( TS_MW
);
1112 } catch ( TimestampException
$e ) {
1113 // Invalid timestamp, ignore it
1119 $this->getRequest()->response()->statusHeader( 304 );
1121 // Avoid outputting the compressed representation of a zero-length body
1122 MediaWiki\
suppressWarnings();
1123 ini_set( 'zlib.output_compression', 0 );
1124 MediaWiki\restoreWarnings
();
1125 wfClearOutputBuffers();
1134 * Check for sufficient permissions to execute
1135 * @param ApiBase $module An Api module
1137 protected function checkExecutePermissions( $module ) {
1138 $user = $this->getUser();
1139 if ( $module->isReadMode() && !User
::isEveryoneAllowed( 'read' ) &&
1140 !$user->isAllowed( 'read' )
1142 $this->dieUsageMsg( 'readrequired' );
1145 if ( $module->isWriteMode() ) {
1146 if ( !$this->mEnableWrite
) {
1147 $this->dieUsageMsg( 'writedisabled' );
1148 } elseif ( !$user->isAllowed( 'writeapi' ) ) {
1149 $this->dieUsageMsg( 'writerequired' );
1150 } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) {
1152 "Promise-Non-Write-API-Action HTTP header cannot be sent to write API modules",
1153 'promised-nonwrite-api'
1157 $this->checkReadOnly( $module );
1160 // Allow extensions to stop execution for arbitrary reasons.
1162 if ( !Hooks
::run( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
1163 $this->dieUsageMsg( $message );
1168 * Check if the DB is read-only for this user
1169 * @param ApiBase $module An Api module
1171 protected function checkReadOnly( $module ) {
1172 if ( wfReadOnly() ) {
1173 $this->dieReadOnly();
1176 if ( $module->isWriteMode()
1177 && in_array( 'bot', $this->getUser()->getGroups() )
1178 && wfGetLB()->getServerCount() > 1
1180 // Figure out how many servers have passed the lag threshold
1182 $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' );
1183 foreach ( wfGetLB()->getLagTimes() as $lag ) {
1184 if ( $lag > $lagLimit ) {
1188 // If a majority of slaves are too lagged then disallow writes
1189 $slaveCount = wfGetLB()->getServerCount() - 1;
1190 if ( $numLagged >= ceil( $slaveCount / 2 ) ) {
1191 $parsed = $this->parseMsg( array( 'readonlytext' ) );
1197 array( 'readonlyreason' => "Waiting for $numLagged lagged database(s)" )
1204 * Check asserts of the user's rights
1205 * @param array $params
1207 protected function checkAsserts( $params ) {
1208 if ( isset( $params['assert'] ) ) {
1209 $user = $this->getUser();
1210 switch ( $params['assert'] ) {
1212 if ( $user->isAnon() ) {
1213 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
1217 if ( !$user->isAllowed( 'bot' ) ) {
1218 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
1226 * Check POST for external response and setup result printer
1227 * @param ApiBase $module An Api module
1228 * @param array $params An array with the request parameters
1230 protected function setupExternalResponse( $module, $params ) {
1231 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
1232 // Module requires POST. GET request might still be allowed
1233 // if $wgDebugApi is true, otherwise fail.
1234 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction
) );
1237 // See if custom printer is used
1238 $this->mPrinter
= $module->getCustomPrinter();
1239 if ( is_null( $this->mPrinter
) ) {
1240 // Create an appropriate printer
1241 $this->mPrinter
= $this->createPrinterByName( $params['format'] );
1246 * Execute the actual module, without any error handling
1248 protected function executeAction() {
1249 $params = $this->setupExecuteAction();
1250 $module = $this->setupModule();
1251 $this->mModule
= $module;
1253 $this->checkExecutePermissions( $module );
1255 if ( !$this->checkMaxLag( $module, $params ) ) {
1259 if ( !$this->checkConditionalRequestHeaders( $module ) ) {
1263 if ( !$this->mInternalMode
) {
1264 $this->setupExternalResponse( $module, $params );
1267 $this->checkAsserts( $params );
1271 Hooks
::run( 'APIAfterExecute', array( &$module ) );
1273 $this->reportUnusedParams();
1275 if ( !$this->mInternalMode
) {
1276 // append Debug information
1277 MWDebug
::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1279 // Print result data
1280 $this->printResult( false );
1285 * Log the preceding request
1286 * @param float $time Time in seconds
1288 protected function logRequest( $time ) {
1289 $request = $this->getRequest();
1291 'dt' => date( 'c' ),
1292 'client_ip' => $request->getIP(),
1293 'user_agent' => $this->getUserAgent(),
1294 'wiki' => wfWikiId(),
1295 'time_backend_ms' => round( $time * 1000 ),
1296 'params' => array(),
1299 // Construct space separated message for 'api' log channel
1300 $msg = "API {$request->getMethod()} " .
1301 wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1302 " {$logCtx['client_ip']} " .
1303 "T={$logCtx['time_backend_ms']}ms";
1305 foreach ( $this->getParamsUsed() as $name ) {
1306 $value = $request->getVal( $name );
1307 if ( $value === null ) {
1311 if ( strlen( $value ) > 256 ) {
1312 $value = substr( $value, 0, 256 );
1313 $encValue = $this->encodeRequestLogValue( $value ) . '[...]';
1315 $encValue = $this->encodeRequestLogValue( $value );
1318 $logCtx['params'][$name] = $value;
1319 $msg .= " {$name}={$encValue}";
1322 wfDebugLog( 'api', $msg, 'private' );
1323 // ApiRequest channel is for structured data consumers
1324 wfDebugLog( 'ApiRequest', '', 'private', $logCtx );
1328 * Encode a value in a format suitable for a space-separated log line.
1332 protected function encodeRequestLogValue( $s ) {
1335 $chars = ';@$!*(),/:';
1336 $numChars = strlen( $chars );
1337 for ( $i = 0; $i < $numChars; $i++
) {
1338 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1342 return strtr( rawurlencode( $s ), $table );
1346 * Get the request parameters used in the course of the preceding execute() request
1349 protected function getParamsUsed() {
1350 return array_keys( $this->mParamsUsed
);
1354 * Get a request value, and register the fact that it was used, for logging.
1355 * @param string $name
1356 * @param mixed $default
1359 public function getVal( $name, $default = null ) {
1360 $this->mParamsUsed
[$name] = true;
1362 $ret = $this->getRequest()->getVal( $name );
1363 if ( $ret === null ) {
1364 if ( $this->getRequest()->getArray( $name ) !== null ) {
1365 // See bug 10262 for why we don't just join( '|', ... ) the
1368 "Parameter '$name' uses unsupported PHP array syntax"
1377 * Get a boolean request value, and register the fact that the parameter
1378 * was used, for logging.
1379 * @param string $name
1382 public function getCheck( $name ) {
1383 return $this->getVal( $name, null ) !== null;
1387 * Get a request upload, and register the fact that it was used, for logging.
1390 * @param string $name Parameter name
1391 * @return WebRequestUpload
1393 public function getUpload( $name ) {
1394 $this->mParamsUsed
[$name] = true;
1396 return $this->getRequest()->getUpload( $name );
1400 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1401 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1403 protected function reportUnusedParams() {
1404 $paramsUsed = $this->getParamsUsed();
1405 $allParams = $this->getRequest()->getValueNames();
1407 if ( !$this->mInternalMode
) {
1408 // Printer has not yet executed; don't warn that its parameters are unused
1409 $printerParams = array_map(
1410 array( $this->mPrinter
, 'encodeParamName' ),
1411 array_keys( $this->mPrinter
->getFinalParams() ?
: array() )
1413 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1415 $unusedParams = array_diff( $allParams, $paramsUsed );
1418 if ( count( $unusedParams ) ) {
1419 $s = count( $unusedParams ) > 1 ?
's' : '';
1420 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1425 * Print results using the current printer
1427 * @param bool $isError
1429 protected function printResult( $isError ) {
1430 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1431 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1434 $printer = $this->mPrinter
;
1435 $printer->initPrinter( false );
1436 $printer->execute();
1437 $printer->closePrinter();
1443 public function isReadMode() {
1448 * See ApiBase for description.
1452 public function getAllowedParams() {
1455 ApiBase
::PARAM_DFLT
=> 'help',
1456 ApiBase
::PARAM_TYPE
=> 'submodule',
1459 ApiBase
::PARAM_DFLT
=> ApiMain
::API_DEFAULT_FORMAT
,
1460 ApiBase
::PARAM_TYPE
=> 'submodule',
1463 ApiBase
::PARAM_TYPE
=> 'integer'
1466 ApiBase
::PARAM_TYPE
=> 'integer',
1467 ApiBase
::PARAM_DFLT
=> 0
1470 ApiBase
::PARAM_TYPE
=> 'integer',
1471 ApiBase
::PARAM_DFLT
=> 0
1474 ApiBase
::PARAM_TYPE
=> array( 'user', 'bot' )
1476 'requestid' => null,
1477 'servedby' => false,
1478 'curtimestamp' => false,
1481 ApiBase
::PARAM_DFLT
=> 'user',
1486 /** @see ApiBase::getExamplesMessages() */
1487 protected function getExamplesMessages() {
1490 => 'apihelp-help-example-main',
1491 'action=help&recursivesubmodules=1'
1492 => 'apihelp-help-example-recursive',
1496 public function modifyHelp( array &$help, array $options, array &$tocData ) {
1497 // Wish PHP had an "array_insert_before". Instead, we have to manually
1498 // reindex the array to get 'permissions' in the right place.
1501 foreach ( $oldHelp as $k => $v ) {
1502 if ( $k === 'submodules' ) {
1503 $help['permissions'] = '';
1507 $help['datatypes'] = '';
1508 $help['credits'] = '';
1510 // Fill 'permissions'
1511 $help['permissions'] .= Html
::openElement( 'div',
1512 array( 'class' => 'apihelp-block apihelp-permissions' ) );
1513 $m = $this->msg( 'api-help-permissions' );
1514 if ( !$m->isDisabled() ) {
1515 $help['permissions'] .= Html
::rawElement( 'div', array( 'class' => 'apihelp-block-head' ),
1516 $m->numParams( count( self
::$mRights ) )->parse()
1519 $help['permissions'] .= Html
::openElement( 'dl' );
1520 foreach ( self
::$mRights as $right => $rightMsg ) {
1521 $help['permissions'] .= Html
::element( 'dt', null, $right );
1523 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1524 $help['permissions'] .= Html
::rawElement( 'dd', null, $rightMsg );
1526 $groups = array_map( function ( $group ) {
1527 return $group == '*' ?
'all' : $group;
1528 }, User
::getGroupsWithPermission( $right ) );
1530 $help['permissions'] .= Html
::rawElement( 'dd', null,
1531 $this->msg( 'api-help-permissions-granted-to' )
1532 ->numParams( count( $groups ) )
1533 ->params( $this->getLanguage()->commaList( $groups ) )
1537 $help['permissions'] .= Html
::closeElement( 'dl' );
1538 $help['permissions'] .= Html
::closeElement( 'div' );
1540 // Fill 'datatypes' and 'credits', if applicable
1541 if ( empty( $options['nolead'] ) ) {
1542 $level = $options['headerlevel'];
1543 $tocnumber = &$options['tocnumber'];
1545 $header = $this->msg( 'api-help-datatypes-header' )->parse();
1546 $help['datatypes'] .= Html
::rawElement( 'h' . min( 6, $level ),
1547 array( 'id' => 'main/datatypes', 'class' => 'apihelp-header' ),
1548 Html
::element( 'span', array( 'id' => Sanitizer
::escapeId( 'main/datatypes' ) ) ) .
1551 $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock();
1552 if ( !isset( $tocData['main/datatypes'] ) ) {
1553 $tocnumber[$level]++
;
1554 $tocData['main/datatypes'] = array(
1555 'toclevel' => count( $tocnumber ),
1557 'anchor' => 'main/datatypes',
1559 'number' => join( '.', $tocnumber ),
1564 $header = $this->msg( 'api-credits-header' )->parse();
1565 $help['credits'] .= Html
::rawElement( 'h' . min( 6, $level ),
1566 array( 'id' => 'main/credits', 'class' => 'apihelp-header' ),
1567 Html
::element( 'span', array( 'id' => Sanitizer
::escapeId( 'main/credits' ) ) ) .
1570 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1571 if ( !isset( $tocData['main/credits'] ) ) {
1572 $tocnumber[$level]++
;
1573 $tocData['main/credits'] = array(
1574 'toclevel' => count( $tocnumber ),
1576 'anchor' => 'main/credits',
1578 'number' => join( '.', $tocnumber ),
1585 private $mCanApiHighLimits = null;
1588 * Check whether the current user is allowed to use high limits
1591 public function canApiHighLimits() {
1592 if ( !isset( $this->mCanApiHighLimits
) ) {
1593 $this->mCanApiHighLimits
= $this->getUser()->isAllowed( 'apihighlimits' );
1596 return $this->mCanApiHighLimits
;
1600 * Overrides to return this instance's module manager.
1601 * @return ApiModuleManager
1603 public function getModuleManager() {
1604 return $this->mModuleMgr
;
1608 * Fetches the user agent used for this request
1610 * The value will be the combination of the 'Api-User-Agent' header (if
1611 * any) and the standard User-Agent header (if any).
1615 public function getUserAgent() {
1617 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1618 $this->getRequest()->getHeader( 'User-agent' )
1622 /************************************************************************//**
1628 * Sets whether the pretty-printer should format *bold* and $italics$
1630 * @deprecated since 1.25
1633 public function setHelp( $help = true ) {
1634 wfDeprecated( __METHOD__
, '1.25' );
1635 $this->mPrinter
->setHelp( $help );
1639 * Override the parent to generate help messages for all available modules.
1641 * @deprecated since 1.25
1644 public function makeHelpMsg() {
1645 wfDeprecated( __METHOD__
, '1.25' );
1648 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1650 return ObjectCache
::getMainWANInstance()->getWithSetCallback(
1653 $this->getModuleName(),
1654 str_replace( ' ', '_', SpecialVersion
::getVersion( 'nodb' ) )
1656 $cacheHelpTimeout > 0 ?
$cacheHelpTimeout : WANObjectCache
::TTL_UNCACHEABLE
,
1657 array( $this, 'reallyMakeHelpMsg' )
1662 * @deprecated since 1.25
1663 * @return mixed|string
1665 public function reallyMakeHelpMsg() {
1666 wfDeprecated( __METHOD__
, '1.25' );
1669 // Use parent to make default message for the main module
1670 $msg = parent
::makeHelpMsg();
1672 $astriks = str_repeat( '*** ', 14 );
1673 $msg .= "\n\n$astriks Modules $astriks\n\n";
1675 foreach ( $this->mModuleMgr
->getNames( 'action' ) as $name ) {
1676 $module = $this->mModuleMgr
->getModule( $name );
1677 $msg .= self
::makeHelpMsgHeader( $module, 'action' );
1679 $msg2 = $module->makeHelpMsg();
1680 if ( $msg2 !== false ) {
1686 $msg .= "\n$astriks Permissions $astriks\n\n";
1687 foreach ( self
::$mRights as $right => $rightMsg ) {
1688 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1689 ->useDatabase( false )
1690 ->inLanguage( 'en' )
1692 $groups = User
::getGroupsWithPermission( $right );
1693 $msg .= "* " . $right . " *\n $rightsMsg" .
1694 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1697 $msg .= "\n$astriks Formats $astriks\n\n";
1698 foreach ( $this->mModuleMgr
->getNames( 'format' ) as $name ) {
1699 $module = $this->mModuleMgr
->getModule( $name );
1700 $msg .= self
::makeHelpMsgHeader( $module, 'format' );
1701 $msg2 = $module->makeHelpMsg();
1702 if ( $msg2 !== false ) {
1708 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1709 $credits = str_replace( "\n", "\n ", $credits );
1710 $msg .= "\n*** Credits: ***\n $credits\n";
1716 * @deprecated since 1.25
1717 * @param ApiBase $module
1718 * @param string $paramName What type of request is this? e.g. action,
1719 * query, list, prop, meta, format
1722 public static function makeHelpMsgHeader( $module, $paramName ) {
1723 wfDeprecated( __METHOD__
, '1.25' );
1724 $modulePrefix = $module->getModulePrefix();
1725 if ( strval( $modulePrefix ) !== '' ) {
1726 $modulePrefix = "($modulePrefix) ";
1729 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1733 * Check whether the user wants us to show version information in the API help
1735 * @deprecated since 1.21, always returns false
1737 public function getShowVersions() {
1738 wfDeprecated( __METHOD__
, '1.21' );
1744 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1745 * classes who wish to add their own modules to their lexicon or override the
1746 * behavior of inherent ones.
1748 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1749 * @param string $name The identifier for this module.
1750 * @param ApiBase $class The class where this module is implemented.
1752 protected function addModule( $name, $class ) {
1753 $this->getModuleManager()->addModule( $name, 'action', $class );
1757 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1758 * classes who wish to add to or modify current formatters.
1760 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1761 * @param string $name The identifier for this format.
1762 * @param ApiFormatBase $class The class implementing this format.
1764 protected function addFormat( $name, $class ) {
1765 $this->getModuleManager()->addModule( $name, 'format', $class );
1769 * Get the array mapping module names to class names
1770 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1773 function getModules() {
1774 return $this->getModuleManager()->getNamesWithClasses( 'action' );
1778 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1781 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1784 public function getFormats() {
1785 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1793 * This exception will be thrown when dieUsage is called to stop module execution.
1797 class UsageException
extends MWException
{
1804 private $mExtraData;
1807 * @param string $message
1808 * @param string $codestr
1810 * @param array|null $extradata
1812 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1813 parent
::__construct( $message, $code );
1814 $this->mCodestr
= $codestr;
1815 $this->mExtraData
= $extradata;
1821 public function getCodeString() {
1822 return $this->mCodestr
;
1828 public function getMessageArray() {
1830 'code' => $this->mCodestr
,
1831 'info' => $this->getMessage()
1833 if ( is_array( $this->mExtraData
) ) {
1834 $result = array_merge( $result, $this->mExtraData
);
1843 public function __toString() {
1844 return "{$this->getCodeString()}: {$this->getMessage()}";
1849 * For really cool vim folding this needs to be at the end:
1850 * vim: foldmarker=@{,@} foldmethod=marker