Localisation updates from https://translatewiki.net.
[mediawiki.git] / includes / api / ApiMain.php
blobd5cd475a5fbc14427458a7e0cda5c9278c8e714d
1 <?php
2 /**
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
24 * @file
25 * @defgroup API API
28 /**
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.
39 * @ingroup API
41 class ApiMain extends ApiBase {
42 /**
43 * When no format parameter is given, this format will be used
45 const API_DEFAULT_FORMAT = 'jsonfm';
47 /**
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',
62 'help' => 'ApiHelp',
63 'paraminfo' => 'ApiParamInfo',
64 'rsd' => 'ApiRsd',
65 'compare' => 'ApiComparePages',
66 'tokens' => 'ApiTokens',
67 'checktoken' => 'ApiCheckToken',
69 // Write modules
70 'purge' => 'ApiPurge',
71 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
72 'rollback' => 'ApiRollback',
73 'delete' => 'ApiDelete',
74 'undelete' => 'ApiUndelete',
75 'protect' => 'ApiProtect',
76 'block' => 'ApiBlock',
77 'unblock' => 'ApiUnblock',
78 'move' => 'ApiMove',
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',
94 /**
95 * List of available formats: format name => format class
97 private static $Formats = array(
98 'json' => 'ApiFormatJson',
99 'jsonfm' => 'ApiFormatJson',
100 'php' => 'ApiFormatPhp',
101 'phpfm' => 'ApiFormatPhp',
102 'wddx' => 'ApiFormatWddx',
103 'wddxfm' => 'ApiFormatWddx',
104 'xml' => 'ApiFormatXml',
105 'xmlfm' => 'ApiFormatXml',
106 'yaml' => 'ApiFormatYaml',
107 'yamlfm' => 'ApiFormatYaml',
108 'rawfm' => 'ApiFormatJson',
109 'txt' => 'ApiFormatTxt',
110 'txtfm' => 'ApiFormatTxt',
111 'dbg' => 'ApiFormatDbg',
112 'dbgfm' => 'ApiFormatDbg',
113 'dump' => 'ApiFormatDump',
114 'dumpfm' => 'ApiFormatDump',
115 'none' => 'ApiFormatNone',
118 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
120 * List of user roles that are specifically relevant to the API.
121 * array( 'right' => array ( 'msg' => 'Some message with a $1',
122 * 'params' => array ( $someVarToSubst ) ),
123 * );
125 private static $mRights = array(
126 'writeapi' => array(
127 'msg' => 'right-writeapi',
128 'params' => array()
130 'apihighlimits' => array(
131 'msg' => 'api-help-right-apihighlimits',
132 'params' => array( ApiBase::LIMIT_SML2, ApiBase::LIMIT_BIG2 )
135 // @codingStandardsIgnoreEnd
138 * @var ApiFormatBase
140 private $mPrinter;
142 private $mModuleMgr, $mResult;
143 private $mAction;
144 private $mEnableWrite;
145 private $mInternalMode, $mSquidMaxage, $mModule;
147 private $mCacheMode = 'private';
148 private $mCacheControl = array();
149 private $mParamsUsed = array();
152 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
154 * @param IContextSource|WebRequest $context If this is an instance of
155 * FauxRequest, errors are thrown and no printing occurs
156 * @param bool $enableWrite Should be set to true if the api may modify data
158 public function __construct( $context = null, $enableWrite = false ) {
159 if ( $context === null ) {
160 $context = RequestContext::getMain();
161 } elseif ( $context instanceof WebRequest ) {
162 // BC for pre-1.19
163 $request = $context;
164 $context = RequestContext::getMain();
166 // We set a derivative context so we can change stuff later
167 $this->setContext( new DerivativeContext( $context ) );
169 if ( isset( $request ) ) {
170 $this->getContext()->setRequest( $request );
173 $this->mInternalMode = ( $this->getRequest() instanceof FauxRequest );
175 // Special handling for the main module: $parent === $this
176 parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
178 if ( !$this->mInternalMode ) {
179 // Impose module restrictions.
180 // If the current user cannot read,
181 // Remove all modules other than login
182 global $wgUser;
184 if ( $this->lacksSameOriginSecurity() ) {
185 // If we're in a mode that breaks the same-origin policy, strip
186 // user credentials for security.
187 wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" );
188 $wgUser = new User();
189 $this->getContext()->setUser( $wgUser );
193 $uselang = $this->getParameter( 'uselang' );
194 if ( $uselang === 'user' ) {
195 // Assume the parent context is going to return the user language
196 // for uselang=user (see T85635).
197 } else {
198 if ( $uselang === 'content' ) {
199 global $wgContLang;
200 $uselang = $wgContLang->getCode();
202 $code = RequestContext::sanitizeLangCode( $uselang );
203 $this->getContext()->setLanguage( $code );
204 if ( !$this->mInternalMode ) {
205 global $wgLang;
206 $wgLang = $this->getContext()->getLanguage();
207 RequestContext::getMain()->setLanguage( $wgLang );
211 $config = $this->getConfig();
212 $this->mModuleMgr = new ApiModuleManager( $this );
213 $this->mModuleMgr->addModules( self::$Modules, 'action' );
214 $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' );
215 $this->mModuleMgr->addModules( self::$Formats, 'format' );
216 $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );
218 Hooks::run( 'ApiMain::moduleManager', array( $this->mModuleMgr ) );
220 $this->mResult = new ApiResult( $this );
221 $this->mEnableWrite = $enableWrite;
223 $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling()
224 $this->mCommit = false;
228 * Return true if the API was started by other PHP code using FauxRequest
229 * @return bool
231 public function isInternalMode() {
232 return $this->mInternalMode;
236 * Get the ApiResult object associated with current request
238 * @return ApiResult
240 public function getResult() {
241 return $this->mResult;
245 * Get the API module object. Only works after executeAction()
247 * @return ApiBase
249 public function getModule() {
250 return $this->mModule;
254 * Get the result formatter object. Only works after setupExecuteAction()
256 * @return ApiFormatBase
258 public function getPrinter() {
259 return $this->mPrinter;
263 * Set how long the response should be cached.
265 * @param int $maxage
267 public function setCacheMaxAge( $maxage ) {
268 $this->setCacheControl( array(
269 'max-age' => $maxage,
270 's-maxage' => $maxage
271 ) );
275 * Set the type of caching headers which will be sent.
277 * @param string $mode One of:
278 * - 'public': Cache this object in public caches, if the maxage or smaxage
279 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
280 * not provided by any of these means, the object will be private.
281 * - 'private': Cache this object only in private client-side caches.
282 * - 'anon-public-user-private': Make this object cacheable for logged-out
283 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
284 * set consistently for a given URL, it cannot be set differently depending on
285 * things like the contents of the database, or whether the user is logged in.
287 * If the wiki does not allow anonymous users to read it, the mode set here
288 * will be ignored, and private caching headers will always be sent. In other words,
289 * the "public" mode is equivalent to saying that the data sent is as public as a page
290 * view.
292 * For user-dependent data, the private mode should generally be used. The
293 * anon-public-user-private mode should only be used where there is a particularly
294 * good performance reason for caching the anonymous response, but where the
295 * response to logged-in users may differ, or may contain private data.
297 * If this function is never called, then the default will be the private mode.
299 public function setCacheMode( $mode ) {
300 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
301 wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" );
303 // Ignore for forwards-compatibility
304 return;
307 if ( !User::isEveryoneAllowed( 'read' ) ) {
308 // Private wiki, only private headers
309 if ( $mode !== 'private' ) {
310 wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" );
312 return;
316 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
317 // User language is used for i18n, so we don't want to publicly
318 // cache. Anons are ok, because if they have non-default language
319 // then there's an appropriate Vary header set by whatever set
320 // their non-default language.
321 wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .
322 "'anon-public-user-private' due to uselang=user\n" );
323 $mode = 'anon-public-user-private';
326 wfDebug( __METHOD__ . ": setting cache mode $mode\n" );
327 $this->mCacheMode = $mode;
331 * Set directives (key/value pairs) for the Cache-Control header.
332 * Boolean values will be formatted as such, by including or omitting
333 * without an equals sign.
335 * Cache control values set here will only be used if the cache mode is not
336 * private, see setCacheMode().
338 * @param array $directives
340 public function setCacheControl( $directives ) {
341 $this->mCacheControl = $directives + $this->mCacheControl;
345 * Create an instance of an output formatter by its name
347 * @param string $format
349 * @return ApiFormatBase
351 public function createPrinterByName( $format ) {
352 $printer = $this->mModuleMgr->getModule( $format, 'format' );
353 if ( $printer === null ) {
354 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
357 return $printer;
361 * Execute api request. Any errors will be handled if the API was called by the remote client.
363 public function execute() {
364 $this->profileIn();
365 if ( $this->mInternalMode ) {
366 $this->executeAction();
367 } else {
368 $this->executeActionWithErrorHandling();
371 $this->profileOut();
375 * Execute an action, and in case of an error, erase whatever partial results
376 * have been accumulated, and replace it with an error message and a help screen.
378 protected function executeActionWithErrorHandling() {
379 // Verify the CORS header before executing the action
380 if ( !$this->handleCORS() ) {
381 // handleCORS() has sent a 403, abort
382 return;
385 // Exit here if the request method was OPTIONS
386 // (assume there will be a followup GET or POST)
387 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
388 return;
391 // In case an error occurs during data output,
392 // clear the output buffer and print just the error information
393 ob_start();
395 $t = microtime( true );
396 try {
397 $this->executeAction();
398 } catch ( Exception $e ) {
399 $this->handleException( $e );
402 // Log the request whether or not there was an error
403 $this->logRequest( microtime( true ) - $t );
405 // Send cache headers after any code which might generate an error, to
406 // avoid sending public cache headers for errors.
407 $this->sendCacheHeaders();
409 ob_end_flush();
413 * Handle an exception as an API response
415 * @since 1.23
416 * @param Exception $e
418 protected function handleException( Exception $e ) {
419 // Bug 63145: Rollback any open database transactions
420 if ( !( $e instanceof UsageException ) ) {
421 // UsageExceptions are intentional, so don't rollback if that's the case
422 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
425 // Allow extra cleanup and logging
426 Hooks::run( 'ApiMain::onException', array( $this, $e ) );
428 // Log it
429 if ( !( $e instanceof UsageException ) ) {
430 MWExceptionHandler::logException( $e );
433 // Handle any kind of exception by outputting properly formatted error message.
434 // If this fails, an unhandled exception should be thrown so that global error
435 // handler will process and log it.
437 $errCode = $this->substituteResultWithError( $e );
439 // Error results should not be cached
440 $this->setCacheMode( 'private' );
442 $response = $this->getRequest()->response();
443 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
444 if ( $e->getCode() === 0 ) {
445 $response->header( $headerStr );
446 } else {
447 $response->header( $headerStr, true, $e->getCode() );
450 // Reset and print just the error message
451 ob_clean();
453 // If the error occurred during printing, do a printer->profileOut()
454 $this->mPrinter->safeProfileOut();
455 $this->printResult( true );
459 * Handle an exception from the ApiBeforeMain hook.
461 * This tries to print the exception as an API response, to be more
462 * friendly to clients. If it fails, it will rethrow the exception.
464 * @since 1.23
465 * @param Exception $e
466 * @throws Exception
468 public static function handleApiBeforeMainException( Exception $e ) {
469 ob_start();
471 try {
472 $main = new self( RequestContext::getMain(), false );
473 $main->handleException( $e );
474 } catch ( Exception $e2 ) {
475 // Nope, even that didn't work. Punt.
476 throw $e;
479 // Log the request and reset cache headers
480 $main->logRequest( 0 );
481 $main->sendCacheHeaders();
483 ob_end_flush();
487 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
489 * If no origin parameter is present, nothing happens.
490 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
491 * is set and false is returned.
492 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
493 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
494 * headers are set.
495 * http://www.w3.org/TR/cors/#resource-requests
496 * http://www.w3.org/TR/cors/#resource-preflight-requests
498 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
500 protected function handleCORS() {
501 $originParam = $this->getParameter( 'origin' ); // defaults to null
502 if ( $originParam === null ) {
503 // No origin parameter, nothing to do
504 return true;
507 $request = $this->getRequest();
508 $response = $request->response();
510 // Origin: header is a space-separated list of origins, check all of them
511 $originHeader = $request->getHeader( 'Origin' );
512 if ( $originHeader === false ) {
513 $origins = array();
514 } else {
515 $originHeader = trim( $originHeader );
516 $origins = preg_split( '/\s+/', $originHeader );
519 if ( !in_array( $originParam, $origins ) ) {
520 // origin parameter set but incorrect
521 // Send a 403 response
522 $message = HttpStatus::getMessage( 403 );
523 $response->header( "HTTP/1.1 403 $message", true, 403 );
524 $response->header( 'Cache-Control: no-cache' );
525 echo "'origin' parameter does not match Origin header\n";
527 return false;
530 $config = $this->getConfig();
531 $matchOrigin = count( $origins ) === 1 && self::matchOrigin(
532 $originParam,
533 $config->get( 'CrossSiteAJAXdomains' ),
534 $config->get( 'CrossSiteAJAXdomainExceptions' )
537 if ( $matchOrigin ) {
538 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
539 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
540 if ( $preflight ) {
541 // This is a CORS preflight request
542 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
543 // If method is not a case-sensitive match, do not set any additional headers and terminate.
544 return true;
546 // We allow the actual request to send the following headers
547 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
548 if ( $requestedHeaders !== false ) {
549 if ( !self::matchRequestedHeaders( $requestedHeaders ) ) {
550 return true;
552 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
555 // We only allow the actual request to be GET or POST
556 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
559 $response->header( "Access-Control-Allow-Origin: $originHeader" );
560 $response->header( 'Access-Control-Allow-Credentials: true' );
561 $response->header( "Timing-Allow-Origin: $originHeader" ); # http://www.w3.org/TR/resource-timing/#timing-allow-origin
563 if ( !$preflight ) {
564 $response->header( 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag' );
568 $this->getOutput()->addVaryHeader( 'Origin' );
569 return true;
573 * Attempt to match an Origin header against a set of rules and a set of exceptions
574 * @param string $value Origin header
575 * @param array $rules Set of wildcard rules
576 * @param array $exceptions Set of wildcard rules
577 * @return bool True if $value matches a rule in $rules and doesn't match
578 * any rules in $exceptions, false otherwise
580 protected static function matchOrigin( $value, $rules, $exceptions ) {
581 foreach ( $rules as $rule ) {
582 if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
583 // Rule matches, check exceptions
584 foreach ( $exceptions as $exc ) {
585 if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
586 return false;
590 return true;
594 return false;
598 * Attempt to validate the value of Access-Control-Request-Headers against a list
599 * of headers that we allow the follow up request to send.
601 * @param string $requestedHeaders Comma seperated list of HTTP headers
602 * @return bool True if all requested headers are in the list of allowed headers
604 protected static function matchRequestedHeaders( $requestedHeaders ) {
605 if ( trim( $requestedHeaders ) === '' ) {
606 return true;
608 $requestedHeaders = explode( ',', $requestedHeaders );
609 $allowedAuthorHeaders = array_flip( array(
610 /* simple headers (see spec) */
611 'accept',
612 'accept-language',
613 'content-language',
614 'content-type',
615 /* non-authorable headers in XHR, which are however requested by some UAs */
616 'accept-encoding',
617 'dnt',
618 'origin',
619 /* MediaWiki whitelist */
620 'api-user-agent',
621 ) );
622 foreach ( $requestedHeaders as $rHeader ) {
623 $rHeader = strtolower( trim( $rHeader ) );
624 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
625 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
626 return false;
629 return true;
633 * Helper function to convert wildcard string into a regex
634 * '*' => '.*?'
635 * '?' => '.'
637 * @param string $wildcard String with wildcards
638 * @return string Regular expression
640 protected static function wildcardToRegex( $wildcard ) {
641 $wildcard = preg_quote( $wildcard, '/' );
642 $wildcard = str_replace(
643 array( '\*', '\?' ),
644 array( '.*?', '.' ),
645 $wildcard
648 return "/^https?:\/\/$wildcard$/";
651 protected function sendCacheHeaders() {
652 $response = $this->getRequest()->response();
653 $out = $this->getOutput();
655 $config = $this->getConfig();
657 if ( $config->get( 'VaryOnXFP' ) ) {
658 $out->addVaryHeader( 'X-Forwarded-Proto' );
661 if ( $this->mCacheMode == 'private' ) {
662 $response->header( 'Cache-Control: private' );
663 return;
666 $useXVO = $config->get( 'UseXVO' );
667 if ( $this->mCacheMode == 'anon-public-user-private' ) {
668 $out->addVaryHeader( 'Cookie' );
669 $response->header( $out->getVaryHeader() );
670 if ( $useXVO ) {
671 $response->header( $out->getXVO() );
672 if ( $out->haveCacheVaryCookies() ) {
673 // Logged in, mark this request private
674 $response->header( 'Cache-Control: private' );
675 return;
677 // Logged out, send normal public headers below
678 } elseif ( session_id() != '' ) {
679 // Logged in or otherwise has session (e.g. anonymous users who have edited)
680 // Mark request private
681 $response->header( 'Cache-Control: private' );
683 return;
684 } // else no XVO and anonymous, send public headers below
687 // Send public headers
688 $response->header( $out->getVaryHeader() );
689 if ( $useXVO ) {
690 $response->header( $out->getXVO() );
693 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
694 if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
695 $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
697 if ( !isset( $this->mCacheControl['max-age'] ) ) {
698 $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
701 if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
702 // Public cache not requested
703 // Sending a Vary header in this case is harmless, and protects us
704 // against conditional calls of setCacheMaxAge().
705 $response->header( 'Cache-Control: private' );
707 return;
710 $this->mCacheControl['public'] = true;
712 // Send an Expires header
713 $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
714 $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
715 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
717 // Construct the Cache-Control header
718 $ccHeader = '';
719 $separator = '';
720 foreach ( $this->mCacheControl as $name => $value ) {
721 if ( is_bool( $value ) ) {
722 if ( $value ) {
723 $ccHeader .= $separator . $name;
724 $separator = ', ';
726 } else {
727 $ccHeader .= $separator . "$name=$value";
728 $separator = ', ';
732 $response->header( "Cache-Control: $ccHeader" );
736 * Replace the result data with the information about an exception.
737 * Returns the error code
738 * @param Exception $e
739 * @return string
741 protected function substituteResultWithError( $e ) {
742 $result = $this->getResult();
744 // Printer may not be initialized if the extractRequestParams() fails for the main module
745 if ( !isset( $this->mPrinter ) ) {
746 // The printer has not been created yet. Try to manually get formatter value.
747 $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
748 if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
749 $value = self::API_DEFAULT_FORMAT;
752 $this->mPrinter = $this->createPrinterByName( $value );
755 // Printer may not be able to handle errors. This is particularly
756 // likely if the module returns something for getCustomPrinter().
757 if ( !$this->mPrinter->canPrintErrors() ) {
758 $this->mPrinter->safeProfileOut();
759 $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
762 // Update raw mode flag for the selected printer.
763 $result->setRawMode( $this->mPrinter->getNeedsRawData() );
765 $config = $this->getConfig();
767 if ( $e instanceof UsageException ) {
768 // User entered incorrect parameters - generate error response
769 $errMessage = $e->getMessageArray();
770 $link = wfExpandUrl( wfScript( 'api' ) );
771 ApiResult::setContent( $errMessage, "See $link for API usage" );
772 } else {
773 // Something is seriously wrong
774 if ( ( $e instanceof DBQueryError ) && !$config->get( 'ShowSQLErrors' ) ) {
775 $info = 'Database query error';
776 } else {
777 $info = "Exception Caught: {$e->getMessage()}";
780 $errMessage = array(
781 'code' => 'internal_api_error_' . get_class( $e ),
782 'info' => '[' . MWExceptionHandler::getLogId( $e ) . '] ' . $info,
784 if ( $config->get( 'ShowExceptionDetails' ) ) {
785 ApiResult::setContent(
786 $errMessage,
787 MWExceptionHandler::getRedactedTraceAsString( $e )
792 // Remember all the warnings to re-add them later
793 $oldResult = $result->getData();
794 $warnings = isset( $oldResult['warnings'] ) ? $oldResult['warnings'] : null;
796 $result->reset();
797 // Re-add the id
798 $requestid = $this->getParameter( 'requestid' );
799 if ( !is_null( $requestid ) ) {
800 $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
802 if ( $config->get( 'ShowHostnames' ) ) {
803 // servedby is especially useful when debugging errors
804 $result->addValue( null, 'servedby', wfHostName(), ApiResult::NO_SIZE_CHECK );
806 if ( $warnings !== null ) {
807 $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
810 $result->addValue( null, 'error', $errMessage, ApiResult::NO_SIZE_CHECK );
812 return $errMessage['code'];
816 * Set up for the execution.
817 * @return array
819 protected function setupExecuteAction() {
820 // First add the id to the top element
821 $result = $this->getResult();
822 $requestid = $this->getParameter( 'requestid' );
823 if ( !is_null( $requestid ) ) {
824 $result->addValue( null, 'requestid', $requestid );
827 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
828 $servedby = $this->getParameter( 'servedby' );
829 if ( $servedby ) {
830 $result->addValue( null, 'servedby', wfHostName() );
834 if ( $this->getParameter( 'curtimestamp' ) ) {
835 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601, time() ),
836 ApiResult::NO_SIZE_CHECK );
839 $params = $this->extractRequestParams();
841 $this->mAction = $params['action'];
843 if ( !is_string( $this->mAction ) ) {
844 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
847 return $params;
851 * Set up the module for response
852 * @return ApiBase The module that will handle this action
853 * @throws MWException
854 * @throws UsageException
856 protected function setupModule() {
857 // Instantiate the module requested by the user
858 $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
859 if ( $module === null ) {
860 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
862 $moduleParams = $module->extractRequestParams();
864 // Check token, if necessary
865 if ( $module->needsToken() === true ) {
866 throw new MWException(
867 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
868 "See documentation for ApiBase::needsToken for details."
871 if ( $module->needsToken() ) {
872 if ( !$module->mustBePosted() ) {
873 throw new MWException(
874 "Module '{$module->getModuleName()}' must require POST to use tokens."
878 if ( !isset( $moduleParams['token'] ) ) {
879 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
882 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
883 array_key_exists(
884 $module->encodeParamName( 'token' ),
885 $this->getRequest()->getQueryValues()
888 $this->dieUsage(
889 "The '{$module->encodeParamName( 'token' )}' parameter was found in the query string, but must be in the POST body",
890 'mustposttoken'
894 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
895 $this->dieUsageMsg( 'sessionfailure' );
899 return $module;
903 * Check the max lag if necessary
904 * @param ApiBase $module Api module being used
905 * @param array $params Array an array containing the request parameters.
906 * @return bool True on success, false should exit immediately
908 protected function checkMaxLag( $module, $params ) {
909 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
910 // Check for maxlag
911 $maxLag = $params['maxlag'];
912 list( $host, $lag ) = wfGetLB()->getMaxLag();
913 if ( $lag > $maxLag ) {
914 $response = $this->getRequest()->response();
916 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
917 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
919 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
920 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
923 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
927 return true;
931 * Check for sufficient permissions to execute
932 * @param ApiBase $module An Api module
934 protected function checkExecutePermissions( $module ) {
935 $user = $this->getUser();
936 if ( $module->isReadMode() && !User::isEveryoneAllowed( 'read' ) &&
937 !$user->isAllowed( 'read' )
939 $this->dieUsageMsg( 'readrequired' );
941 if ( $module->isWriteMode() ) {
942 if ( !$this->mEnableWrite ) {
943 $this->dieUsageMsg( 'writedisabled' );
945 if ( !$user->isAllowed( 'writeapi' ) ) {
946 $this->dieUsageMsg( 'writerequired' );
948 if ( wfReadOnly() ) {
949 $this->dieReadOnly();
953 // Allow extensions to stop execution for arbitrary reasons.
954 $message = false;
955 if ( !Hooks::run( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
956 $this->dieUsageMsg( $message );
961 * Check asserts of the user's rights
962 * @param array $params
964 protected function checkAsserts( $params ) {
965 if ( isset( $params['assert'] ) ) {
966 $user = $this->getUser();
967 switch ( $params['assert'] ) {
968 case 'user':
969 if ( $user->isAnon() ) {
970 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
972 break;
973 case 'bot':
974 if ( !$user->isAllowed( 'bot' ) ) {
975 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
977 break;
983 * Check POST for external response and setup result printer
984 * @param ApiBase $module An Api module
985 * @param array $params An array with the request parameters
987 protected function setupExternalResponse( $module, $params ) {
988 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
989 // Module requires POST. GET request might still be allowed
990 // if $wgDebugApi is true, otherwise fail.
991 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction ) );
994 // See if custom printer is used
995 $this->mPrinter = $module->getCustomPrinter();
996 if ( is_null( $this->mPrinter ) ) {
997 // Create an appropriate printer
998 $this->mPrinter = $this->createPrinterByName( $params['format'] );
1001 if ( $this->mPrinter->getNeedsRawData() ) {
1002 $this->getResult()->setRawMode();
1007 * Execute the actual module, without any error handling
1009 protected function executeAction() {
1010 $params = $this->setupExecuteAction();
1011 $module = $this->setupModule();
1012 $this->mModule = $module;
1014 $this->checkExecutePermissions( $module );
1016 if ( !$this->checkMaxLag( $module, $params ) ) {
1017 return;
1020 if ( !$this->mInternalMode ) {
1021 $this->setupExternalResponse( $module, $params );
1024 $this->checkAsserts( $params );
1026 // Execute
1027 $module->profileIn();
1028 $module->execute();
1029 Hooks::run( 'APIAfterExecute', array( &$module ) );
1030 $module->profileOut();
1032 $this->reportUnusedParams();
1034 if ( !$this->mInternalMode ) {
1035 //append Debug information
1036 MWDebug::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1038 // Print result data
1039 $this->printResult( false );
1044 * Log the preceding request
1045 * @param int $time Time in seconds
1047 protected function logRequest( $time ) {
1048 $request = $this->getRequest();
1049 $milliseconds = $time === null ? '?' : round( $time * 1000 );
1050 $s = 'API' .
1051 ' ' . $request->getMethod() .
1052 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1053 ' ' . $request->getIP() .
1054 ' T=' . $milliseconds . 'ms';
1055 foreach ( $this->getParamsUsed() as $name ) {
1056 $value = $request->getVal( $name );
1057 if ( $value === null ) {
1058 continue;
1060 $s .= ' ' . $name . '=';
1061 if ( strlen( $value ) > 256 ) {
1062 $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
1063 $s .= $encValue . '[...]';
1064 } else {
1065 $s .= $this->encodeRequestLogValue( $value );
1068 $s .= "\n";
1069 wfDebugLog( 'api', $s, 'private' );
1073 * Encode a value in a format suitable for a space-separated log line.
1074 * @param string $s
1075 * @return string
1077 protected function encodeRequestLogValue( $s ) {
1078 static $table;
1079 if ( !$table ) {
1080 $chars = ';@$!*(),/:';
1081 $numChars = strlen( $chars );
1082 for ( $i = 0; $i < $numChars; $i++ ) {
1083 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1087 return strtr( rawurlencode( $s ), $table );
1091 * Get the request parameters used in the course of the preceding execute() request
1092 * @return array
1094 protected function getParamsUsed() {
1095 return array_keys( $this->mParamsUsed );
1099 * Get a request value, and register the fact that it was used, for logging.
1100 * @param string $name
1101 * @param mixed $default
1102 * @return mixed
1104 public function getVal( $name, $default = null ) {
1105 $this->mParamsUsed[$name] = true;
1107 $ret = $this->getRequest()->getVal( $name );
1108 if ( $ret === null ) {
1109 if ( $this->getRequest()->getArray( $name ) !== null ) {
1110 // See bug 10262 for why we don't just join( '|', ... ) the
1111 // array.
1112 $this->setWarning(
1113 "Parameter '$name' uses unsupported PHP array syntax"
1116 $ret = $default;
1118 return $ret;
1122 * Get a boolean request value, and register the fact that the parameter
1123 * was used, for logging.
1124 * @param string $name
1125 * @return bool
1127 public function getCheck( $name ) {
1128 return $this->getVal( $name, null ) !== null;
1132 * Get a request upload, and register the fact that it was used, for logging.
1134 * @since 1.21
1135 * @param string $name Parameter name
1136 * @return WebRequestUpload
1138 public function getUpload( $name ) {
1139 $this->mParamsUsed[$name] = true;
1141 return $this->getRequest()->getUpload( $name );
1145 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1146 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1148 protected function reportUnusedParams() {
1149 $paramsUsed = $this->getParamsUsed();
1150 $allParams = $this->getRequest()->getValueNames();
1152 if ( !$this->mInternalMode ) {
1153 // Printer has not yet executed; don't warn that its parameters are unused
1154 $printerParams = array_map(
1155 array( $this->mPrinter, 'encodeParamName' ),
1156 array_keys( $this->mPrinter->getFinalParams() ?: array() )
1158 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1159 } else {
1160 $unusedParams = array_diff( $allParams, $paramsUsed );
1163 if ( count( $unusedParams ) ) {
1164 $s = count( $unusedParams ) > 1 ? 's' : '';
1165 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1170 * Print results using the current printer
1172 * @param bool $isError
1174 protected function printResult( $isError ) {
1175 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1176 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1179 $this->getResult()->cleanUpUTF8();
1180 $printer = $this->mPrinter;
1181 $printer->profileIn();
1183 $printer->initPrinter( false );
1185 $printer->execute();
1186 $printer->closePrinter();
1187 $printer->profileOut();
1191 * @return bool
1193 public function isReadMode() {
1194 return false;
1198 * See ApiBase for description.
1200 * @return array
1202 public function getAllowedParams() {
1203 return array(
1204 'action' => array(
1205 ApiBase::PARAM_DFLT => 'help',
1206 ApiBase::PARAM_TYPE => 'submodule',
1208 'format' => array(
1209 ApiBase::PARAM_DFLT => ApiMain::API_DEFAULT_FORMAT,
1210 ApiBase::PARAM_TYPE => 'submodule',
1212 'maxlag' => array(
1213 ApiBase::PARAM_TYPE => 'integer'
1215 'smaxage' => array(
1216 ApiBase::PARAM_TYPE => 'integer',
1217 ApiBase::PARAM_DFLT => 0
1219 'maxage' => array(
1220 ApiBase::PARAM_TYPE => 'integer',
1221 ApiBase::PARAM_DFLT => 0
1223 'assert' => array(
1224 ApiBase::PARAM_TYPE => array( 'user', 'bot' )
1226 'requestid' => null,
1227 'servedby' => false,
1228 'curtimestamp' => false,
1229 'origin' => null,
1230 'uselang' => array(
1231 ApiBase::PARAM_DFLT => 'user',
1236 /** @see ApiBase::getExamplesMessages() */
1237 protected function getExamplesMessages() {
1238 return array(
1239 'action=help'
1240 => 'apihelp-help-example-main',
1241 'action=help&recursivesubmodules=1'
1242 => 'apihelp-help-example-recursive',
1246 public function modifyHelp( array &$help, array $options ) {
1247 // Wish PHP had an "array_insert_before". Instead, we have to manually
1248 // reindex the array to get 'permissions' in the right place.
1249 $oldHelp = $help;
1250 $help = array();
1251 foreach ( $oldHelp as $k => $v ) {
1252 if ( $k === 'submodules' ) {
1253 $help['permissions'] = '';
1255 $help[$k] = $v;
1257 $help['credits'] = '';
1259 // Fill 'permissions'
1260 $help['permissions'] .= Html::openElement( 'div',
1261 array( 'class' => 'apihelp-block apihelp-permissions' ) );
1262 $m = $this->msg( 'api-help-permissions' );
1263 if ( !$m->isDisabled() ) {
1264 $help['permissions'] .= Html::rawElement( 'div', array( 'class' => 'apihelp-block-head' ),
1265 $m->numParams( count( self::$mRights ) )->parse()
1268 $help['permissions'] .= Html::openElement( 'dl' );
1269 foreach ( self::$mRights as $right => $rightMsg ) {
1270 $help['permissions'] .= Html::element( 'dt', null, $right );
1272 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1273 $help['permissions'] .= Html::rawElement( 'dd', null, $rightMsg );
1275 $groups = array_map( function ( $group ) {
1276 return $group == '*' ? 'all' : $group;
1277 }, User::getGroupsWithPermission( $right ) );
1279 $help['permissions'] .= Html::rawElement( 'dd', null,
1280 $this->msg( 'api-help-permissions-granted-to' )
1281 ->numParams( count( $groups ) )
1282 ->params( $this->getLanguage()->commaList( $groups ) )
1283 ->parse()
1286 $help['permissions'] .= Html::closeElement( 'dl' );
1287 $help['permissions'] .= Html::closeElement( 'div' );
1289 // Fill 'credits', if applicable
1290 if ( empty( $options['nolead'] ) ) {
1291 $help['credits'] .= Html::element( 'h' . min( 6, $options['headerlevel'] + 1 ),
1292 array( 'id' => '+credits', 'class' => 'apihelp-header' ),
1293 $this->msg( 'api-credits-header' )->parse()
1295 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1299 private $mCanApiHighLimits = null;
1302 * Check whether the current user is allowed to use high limits
1303 * @return bool
1305 public function canApiHighLimits() {
1306 if ( !isset( $this->mCanApiHighLimits ) ) {
1307 $this->mCanApiHighLimits = $this->getUser()->isAllowed( 'apihighlimits' );
1310 return $this->mCanApiHighLimits;
1314 * Overrides to return this instance's module manager.
1315 * @return ApiModuleManager
1317 public function getModuleManager() {
1318 return $this->mModuleMgr;
1322 * Fetches the user agent used for this request
1324 * The value will be the combination of the 'Api-User-Agent' header (if
1325 * any) and the standard User-Agent header (if any).
1327 * @return string
1329 public function getUserAgent() {
1330 return trim(
1331 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1332 $this->getRequest()->getHeader( 'User-agent' )
1336 /************************************************************************//**
1337 * @name Deprecated
1338 * @{
1342 * Sets whether the pretty-printer should format *bold* and $italics$
1344 * @deprecated since 1.25
1345 * @param bool $help
1347 public function setHelp( $help = true ) {
1348 wfDeprecated( __METHOD__, '1.25' );
1349 $this->mPrinter->setHelp( $help );
1353 * Override the parent to generate help messages for all available modules.
1355 * @deprecated since 1.25
1356 * @return string
1358 public function makeHelpMsg() {
1359 wfDeprecated( __METHOD__, '1.25' );
1360 global $wgMemc;
1361 $this->setHelp();
1362 // Get help text from cache if present
1363 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1364 str_replace( ' ', '_', SpecialVersion::getVersion( 'nodb' ) ) );
1366 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1367 if ( $cacheHelpTimeout > 0 ) {
1368 $cached = $wgMemc->get( $key );
1369 if ( $cached ) {
1370 return $cached;
1373 $retval = $this->reallyMakeHelpMsg();
1374 if ( $cacheHelpTimeout > 0 ) {
1375 $wgMemc->set( $key, $retval, $cacheHelpTimeout );
1378 return $retval;
1382 * @deprecated since 1.25
1383 * @return mixed|string
1385 public function reallyMakeHelpMsg() {
1386 wfDeprecated( __METHOD__, '1.25' );
1387 $this->setHelp();
1389 // Use parent to make default message for the main module
1390 $msg = parent::makeHelpMsg();
1392 $astriks = str_repeat( '*** ', 14 );
1393 $msg .= "\n\n$astriks Modules $astriks\n\n";
1395 foreach ( $this->mModuleMgr->getNames( 'action' ) as $name ) {
1396 $module = $this->mModuleMgr->getModule( $name );
1397 $msg .= self::makeHelpMsgHeader( $module, 'action' );
1399 $msg2 = $module->makeHelpMsg();
1400 if ( $msg2 !== false ) {
1401 $msg .= $msg2;
1403 $msg .= "\n";
1406 $msg .= "\n$astriks Permissions $astriks\n\n";
1407 foreach ( self::$mRights as $right => $rightMsg ) {
1408 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1409 ->useDatabase( false )
1410 ->inLanguage( 'en' )
1411 ->text();
1412 $groups = User::getGroupsWithPermission( $right );
1413 $msg .= "* " . $right . " *\n $rightsMsg" .
1414 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1417 $msg .= "\n$astriks Formats $astriks\n\n";
1418 foreach ( $this->mModuleMgr->getNames( 'format' ) as $name ) {
1419 $module = $this->mModuleMgr->getModule( $name );
1420 $msg .= self::makeHelpMsgHeader( $module, 'format' );
1421 $msg2 = $module->makeHelpMsg();
1422 if ( $msg2 !== false ) {
1423 $msg .= $msg2;
1425 $msg .= "\n";
1428 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1429 $credits = str_replace( "\n", "\n ", $credits );
1430 $msg .= "\n*** Credits: ***\n $credits\n";
1432 return $msg;
1436 * @deprecated since 1.25
1437 * @param ApiBase $module
1438 * @param string $paramName What type of request is this? e.g. action,
1439 * query, list, prop, meta, format
1440 * @return string
1442 public static function makeHelpMsgHeader( $module, $paramName ) {
1443 wfDeprecated( __METHOD__, '1.25' );
1444 $modulePrefix = $module->getModulePrefix();
1445 if ( strval( $modulePrefix ) !== '' ) {
1446 $modulePrefix = "($modulePrefix) ";
1449 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1453 * Check whether the user wants us to show version information in the API help
1454 * @return bool
1455 * @deprecated since 1.21, always returns false
1457 public function getShowVersions() {
1458 wfDeprecated( __METHOD__, '1.21' );
1460 return false;
1464 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1465 * classes who wish to add their own modules to their lexicon or override the
1466 * behavior of inherent ones.
1468 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1469 * @param string $name The identifier for this module.
1470 * @param ApiBase $class The class where this module is implemented.
1472 protected function addModule( $name, $class ) {
1473 $this->getModuleManager()->addModule( $name, 'action', $class );
1477 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1478 * classes who wish to add to or modify current formatters.
1480 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1481 * @param string $name The identifier for this format.
1482 * @param ApiFormatBase $class The class implementing this format.
1484 protected function addFormat( $name, $class ) {
1485 $this->getModuleManager()->addModule( $name, 'format', $class );
1489 * Get the array mapping module names to class names
1490 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1491 * @return array
1493 function getModules() {
1494 return $this->getModuleManager()->getNamesWithClasses( 'action' );
1498 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1500 * @since 1.18
1501 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1502 * @return array
1504 public function getFormats() {
1505 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1508 /**@}*/
1513 * This exception will be thrown when dieUsage is called to stop module execution.
1515 * @ingroup API
1517 class UsageException extends MWException {
1519 private $mCodestr;
1522 * @var null|array
1524 private $mExtraData;
1527 * @param string $message
1528 * @param string $codestr
1529 * @param int $code
1530 * @param array|null $extradata
1532 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1533 parent::__construct( $message, $code );
1534 $this->mCodestr = $codestr;
1535 $this->mExtraData = $extradata;
1539 * @return string
1541 public function getCodeString() {
1542 return $this->mCodestr;
1546 * @return array
1548 public function getMessageArray() {
1549 $result = array(
1550 'code' => $this->mCodestr,
1551 'info' => $this->getMessage()
1553 if ( is_array( $this->mExtraData ) ) {
1554 $result = array_merge( $result, $this->mExtraData );
1557 return $result;
1561 * @return string
1563 public function __toString() {
1564 return "{$this->getCodeString()}: {$this->getMessage()}";
1569 * For really cool vim folding this needs to be at the end:
1570 * vim: foldmarker=@{,@} foldmethod=marker