Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / api / ApiMain.php
blobf17b8741bb2bd7ee0a5ef2d8bbba008337d58730
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',
68 // Write modules
69 'purge' => 'ApiPurge',
70 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
71 'rollback' => 'ApiRollback',
72 'delete' => 'ApiDelete',
73 'undelete' => 'ApiUndelete',
74 'protect' => 'ApiProtect',
75 'block' => 'ApiBlock',
76 'unblock' => 'ApiUnblock',
77 'move' => 'ApiMove',
78 'edit' => 'ApiEditPage',
79 'upload' => 'ApiUpload',
80 'filerevert' => 'ApiFileRevert',
81 'emailuser' => 'ApiEmailUser',
82 'watch' => 'ApiWatch',
83 'patrol' => 'ApiPatrol',
84 'import' => 'ApiImport',
85 'clearhasmsg' => 'ApiClearHasMsg',
86 'userrights' => 'ApiUserrights',
87 'options' => 'ApiOptions',
88 'imagerotate' => 'ApiImageRotate',
89 'revisiondelete' => 'ApiRevisionDelete',
90 'managetags' => 'ApiManageTags',
93 /**
94 * List of available formats: format name => format class
96 private static $Formats = array(
97 'json' => 'ApiFormatJson',
98 'jsonfm' => 'ApiFormatJson',
99 'php' => 'ApiFormatPhp',
100 'phpfm' => 'ApiFormatPhp',
101 'wddx' => 'ApiFormatWddx',
102 'wddxfm' => 'ApiFormatWddx',
103 'xml' => 'ApiFormatXml',
104 'xmlfm' => 'ApiFormatXml',
105 'yaml' => 'ApiFormatYaml',
106 'yamlfm' => 'ApiFormatYaml',
107 'rawfm' => 'ApiFormatJson',
108 'txt' => 'ApiFormatTxt',
109 'txtfm' => 'ApiFormatTxt',
110 'dbg' => 'ApiFormatDbg',
111 'dbgfm' => 'ApiFormatDbg',
112 'dump' => 'ApiFormatDump',
113 'dumpfm' => 'ApiFormatDump',
114 'none' => 'ApiFormatNone',
117 // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line
119 * List of user roles that are specifically relevant to the API.
120 * array( 'right' => array ( 'msg' => 'Some message with a $1',
121 * 'params' => array ( $someVarToSubst ) ),
122 * );
124 private static $mRights = array(
125 'writeapi' => array(
126 'msg' => 'right-writeapi',
127 'params' => array()
129 'apihighlimits' => array(
130 'msg' => 'api-help-right-apihighlimits',
131 'params' => array( ApiBase::LIMIT_SML2, ApiBase::LIMIT_BIG2 )
134 // @codingStandardsIgnoreEnd
137 * @var ApiFormatBase
139 private $mPrinter;
141 private $mModuleMgr, $mResult;
142 private $mAction;
143 private $mEnableWrite;
144 private $mInternalMode, $mSquidMaxage, $mModule;
146 private $mCacheMode = 'private';
147 private $mCacheControl = array();
148 private $mParamsUsed = array();
151 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
153 * @param IContextSource|WebRequest $context If this is an instance of
154 * FauxRequest, errors are thrown and no printing occurs
155 * @param bool $enableWrite Should be set to true if the api may modify data
157 public function __construct( $context = null, $enableWrite = false ) {
158 if ( $context === null ) {
159 $context = RequestContext::getMain();
160 } elseif ( $context instanceof WebRequest ) {
161 // BC for pre-1.19
162 $request = $context;
163 $context = RequestContext::getMain();
165 // We set a derivative context so we can change stuff later
166 $this->setContext( new DerivativeContext( $context ) );
168 if ( isset( $request ) ) {
169 $this->getContext()->setRequest( $request );
172 $this->mInternalMode = ( $this->getRequest() instanceof FauxRequest );
174 // Special handling for the main module: $parent === $this
175 parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
177 if ( !$this->mInternalMode ) {
178 // Impose module restrictions.
179 // If the current user cannot read,
180 // Remove all modules other than login
181 global $wgUser;
183 if ( $this->getVal( 'callback' ) !== null ) {
184 // JSON callback allows cross-site reads.
185 // For safety, strip user credentials.
186 wfDebug( "API: stripping user credentials for JSON callback\n" );
187 $wgUser = new User();
188 $this->getContext()->setUser( $wgUser );
192 $uselang = $this->getParameter( 'uselang' );
193 if ( $uselang === 'user' ) {
194 // Assume the parent context is going to return the user language
195 // for uselang=user (see T85635).
196 } else {
197 if ( $uselang === 'content' ) {
198 global $wgContLang;
199 $uselang = $wgContLang->getCode();
201 $code = RequestContext::sanitizeLangCode( $uselang );
202 $this->getContext()->setLanguage( $code );
203 if ( !$this->mInternalMode ) {
204 global $wgLang;
205 $wgLang = $this->getContext()->getLanguage();
206 RequestContext::getMain()->setLanguage( $wgLang );
210 $config = $this->getConfig();
211 $this->mModuleMgr = new ApiModuleManager( $this );
212 $this->mModuleMgr->addModules( self::$Modules, 'action' );
213 $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' );
214 $this->mModuleMgr->addModules( self::$Formats, 'format' );
215 $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' );
217 $this->mResult = new ApiResult( $this );
218 $this->mEnableWrite = $enableWrite;
220 $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling()
221 $this->mCommit = false;
225 * Return true if the API was started by other PHP code using FauxRequest
226 * @return bool
228 public function isInternalMode() {
229 return $this->mInternalMode;
233 * Get the ApiResult object associated with current request
235 * @return ApiResult
237 public function getResult() {
238 return $this->mResult;
242 * Get the API module object. Only works after executeAction()
244 * @return ApiBase
246 public function getModule() {
247 return $this->mModule;
251 * Get the result formatter object. Only works after setupExecuteAction()
253 * @return ApiFormatBase
255 public function getPrinter() {
256 return $this->mPrinter;
260 * Set how long the response should be cached.
262 * @param int $maxage
264 public function setCacheMaxAge( $maxage ) {
265 $this->setCacheControl( array(
266 'max-age' => $maxage,
267 's-maxage' => $maxage
268 ) );
272 * Set the type of caching headers which will be sent.
274 * @param string $mode One of:
275 * - 'public': Cache this object in public caches, if the maxage or smaxage
276 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
277 * not provided by any of these means, the object will be private.
278 * - 'private': Cache this object only in private client-side caches.
279 * - 'anon-public-user-private': Make this object cacheable for logged-out
280 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
281 * set consistently for a given URL, it cannot be set differently depending on
282 * things like the contents of the database, or whether the user is logged in.
284 * If the wiki does not allow anonymous users to read it, the mode set here
285 * will be ignored, and private caching headers will always be sent. In other words,
286 * the "public" mode is equivalent to saying that the data sent is as public as a page
287 * view.
289 * For user-dependent data, the private mode should generally be used. The
290 * anon-public-user-private mode should only be used where there is a particularly
291 * good performance reason for caching the anonymous response, but where the
292 * response to logged-in users may differ, or may contain private data.
294 * If this function is never called, then the default will be the private mode.
296 public function setCacheMode( $mode ) {
297 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
298 wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" );
300 // Ignore for forwards-compatibility
301 return;
304 if ( !User::isEveryoneAllowed( 'read' ) ) {
305 // Private wiki, only private headers
306 if ( $mode !== 'private' ) {
307 wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" );
309 return;
313 if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) {
314 // User language is used for i18n, so we don't want to publicly
315 // cache. Anons are ok, because if they have non-default language
316 // then there's an appropriate Vary header set by whatever set
317 // their non-default language.
318 wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " .
319 "'anon-public-user-private' due to uselang=user\n" );
320 $mode = 'anon-public-user-private';
323 wfDebug( __METHOD__ . ": setting cache mode $mode\n" );
324 $this->mCacheMode = $mode;
328 * Set directives (key/value pairs) for the Cache-Control header.
329 * Boolean values will be formatted as such, by including or omitting
330 * without an equals sign.
332 * Cache control values set here will only be used if the cache mode is not
333 * private, see setCacheMode().
335 * @param array $directives
337 public function setCacheControl( $directives ) {
338 $this->mCacheControl = $directives + $this->mCacheControl;
342 * Create an instance of an output formatter by its name
344 * @param string $format
346 * @return ApiFormatBase
348 public function createPrinterByName( $format ) {
349 $printer = $this->mModuleMgr->getModule( $format, 'format' );
350 if ( $printer === null ) {
351 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
354 return $printer;
358 * Execute api request. Any errors will be handled if the API was called by the remote client.
360 public function execute() {
361 $this->profileIn();
362 if ( $this->mInternalMode ) {
363 $this->executeAction();
364 } else {
365 $this->executeActionWithErrorHandling();
368 $this->profileOut();
372 * Execute an action, and in case of an error, erase whatever partial results
373 * have been accumulated, and replace it with an error message and a help screen.
375 protected function executeActionWithErrorHandling() {
376 // Verify the CORS header before executing the action
377 if ( !$this->handleCORS() ) {
378 // handleCORS() has sent a 403, abort
379 return;
382 // Exit here if the request method was OPTIONS
383 // (assume there will be a followup GET or POST)
384 if ( $this->getRequest()->getMethod() === 'OPTIONS' ) {
385 return;
388 // In case an error occurs during data output,
389 // clear the output buffer and print just the error information
390 ob_start();
392 $t = microtime( true );
393 try {
394 $this->executeAction();
395 } catch ( Exception $e ) {
396 $this->handleException( $e );
399 // Log the request whether or not there was an error
400 $this->logRequest( microtime( true ) - $t );
402 // Send cache headers after any code which might generate an error, to
403 // avoid sending public cache headers for errors.
404 $this->sendCacheHeaders();
406 ob_end_flush();
410 * Handle an exception as an API response
412 * @since 1.23
413 * @param Exception $e
415 protected function handleException( Exception $e ) {
416 // Bug 63145: Rollback any open database transactions
417 if ( !( $e instanceof UsageException ) ) {
418 // UsageExceptions are intentional, so don't rollback if that's the case
419 MWExceptionHandler::rollbackMasterChangesAndLog( $e );
422 // Allow extra cleanup and logging
423 Hooks::run( 'ApiMain::onException', array( $this, $e ) );
425 // Log it
426 if ( !( $e instanceof UsageException ) ) {
427 MWExceptionHandler::logException( $e );
430 // Handle any kind of exception by outputting properly formatted error message.
431 // If this fails, an unhandled exception should be thrown so that global error
432 // handler will process and log it.
434 $errCode = $this->substituteResultWithError( $e );
436 // Error results should not be cached
437 $this->setCacheMode( 'private' );
439 $response = $this->getRequest()->response();
440 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
441 if ( $e->getCode() === 0 ) {
442 $response->header( $headerStr );
443 } else {
444 $response->header( $headerStr, true, $e->getCode() );
447 // Reset and print just the error message
448 ob_clean();
450 // If the error occurred during printing, do a printer->profileOut()
451 $this->mPrinter->safeProfileOut();
452 $this->printResult( true );
456 * Handle an exception from the ApiBeforeMain hook.
458 * This tries to print the exception as an API response, to be more
459 * friendly to clients. If it fails, it will rethrow the exception.
461 * @since 1.23
462 * @param Exception $e
463 * @throws Exception
465 public static function handleApiBeforeMainException( Exception $e ) {
466 ob_start();
468 try {
469 $main = new self( RequestContext::getMain(), false );
470 $main->handleException( $e );
471 } catch ( Exception $e2 ) {
472 // Nope, even that didn't work. Punt.
473 throw $e;
476 // Log the request and reset cache headers
477 $main->logRequest( 0 );
478 $main->sendCacheHeaders();
480 ob_end_flush();
484 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
486 * If no origin parameter is present, nothing happens.
487 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
488 * is set and false is returned.
489 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
490 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
491 * headers are set.
492 * http://www.w3.org/TR/cors/#resource-requests
493 * http://www.w3.org/TR/cors/#resource-preflight-requests
495 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
497 protected function handleCORS() {
498 $originParam = $this->getParameter( 'origin' ); // defaults to null
499 if ( $originParam === null ) {
500 // No origin parameter, nothing to do
501 return true;
504 $request = $this->getRequest();
505 $response = $request->response();
507 // Origin: header is a space-separated list of origins, check all of them
508 $originHeader = $request->getHeader( 'Origin' );
509 if ( $originHeader === false ) {
510 $origins = array();
511 } else {
512 $originHeader = trim( $originHeader );
513 $origins = preg_split( '/\s+/', $originHeader );
516 if ( !in_array( $originParam, $origins ) ) {
517 // origin parameter set but incorrect
518 // Send a 403 response
519 $message = HttpStatus::getMessage( 403 );
520 $response->header( "HTTP/1.1 403 $message", true, 403 );
521 $response->header( 'Cache-Control: no-cache' );
522 echo "'origin' parameter does not match Origin header\n";
524 return false;
527 $config = $this->getConfig();
528 $matchOrigin = count( $origins ) === 1 && self::matchOrigin(
529 $originParam,
530 $config->get( 'CrossSiteAJAXdomains' ),
531 $config->get( 'CrossSiteAJAXdomainExceptions' )
534 if ( $matchOrigin ) {
535 $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' );
536 $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false;
537 if ( $preflight ) {
538 // This is a CORS preflight request
539 if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) {
540 // If method is not a case-sensitive match, do not set any additional headers and terminate.
541 return true;
543 // We allow the actual request to send the following headers
544 $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' );
545 if ( $requestedHeaders !== false ) {
546 if ( !self::matchRequestedHeaders( $requestedHeaders ) ) {
547 return true;
549 $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders );
552 // We only allow the actual request to be GET or POST
553 $response->header( 'Access-Control-Allow-Methods: POST, GET' );
556 $response->header( "Access-Control-Allow-Origin: $originHeader" );
557 $response->header( 'Access-Control-Allow-Credentials: true' );
558 $response->header( "Timing-Allow-Origin: $originHeader" ); # http://www.w3.org/TR/resource-timing/#timing-allow-origin
560 if ( !$preflight ) {
561 $response->header( 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag' );
565 $this->getOutput()->addVaryHeader( 'Origin' );
566 return true;
570 * Attempt to match an Origin header against a set of rules and a set of exceptions
571 * @param string $value Origin header
572 * @param array $rules Set of wildcard rules
573 * @param array $exceptions Set of wildcard rules
574 * @return bool True if $value matches a rule in $rules and doesn't match
575 * any rules in $exceptions, false otherwise
577 protected static function matchOrigin( $value, $rules, $exceptions ) {
578 foreach ( $rules as $rule ) {
579 if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
580 // Rule matches, check exceptions
581 foreach ( $exceptions as $exc ) {
582 if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
583 return false;
587 return true;
591 return false;
595 * Attempt to validate the value of Access-Control-Request-Headers against a list
596 * of headers that we allow the follow up request to send.
598 * @param string $requestedHeaders Comma seperated list of HTTP headers
599 * @return bool True if all requested headers are in the list of allowed headers
601 protected static function matchRequestedHeaders( $requestedHeaders ) {
602 if ( trim( $requestedHeaders ) === '' ) {
603 return true;
605 $requestedHeaders = explode( ',', $requestedHeaders );
606 $allowedAuthorHeaders = array_flip( array(
607 /* simple headers (see spec) */
608 'accept',
609 'accept-language',
610 'content-language',
611 'content-type',
612 /* non-authorable headers in XHR, which are however requested by some UAs */
613 'accept-encoding',
614 'dnt',
615 'origin',
616 /* MediaWiki whitelist */
617 'api-user-agent',
618 ) );
619 foreach ( $requestedHeaders as $rHeader ) {
620 $rHeader = strtolower( trim( $rHeader ) );
621 if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) {
622 wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader );
623 return false;
626 return true;
630 * Helper function to convert wildcard string into a regex
631 * '*' => '.*?'
632 * '?' => '.'
634 * @param string $wildcard String with wildcards
635 * @return string Regular expression
637 protected static function wildcardToRegex( $wildcard ) {
638 $wildcard = preg_quote( $wildcard, '/' );
639 $wildcard = str_replace(
640 array( '\*', '\?' ),
641 array( '.*?', '.' ),
642 $wildcard
645 return "/^https?:\/\/$wildcard$/";
648 protected function sendCacheHeaders() {
649 $response = $this->getRequest()->response();
650 $out = $this->getOutput();
652 $config = $this->getConfig();
654 if ( $config->get( 'VaryOnXFP' ) ) {
655 $out->addVaryHeader( 'X-Forwarded-Proto' );
658 if ( $this->mCacheMode == 'private' ) {
659 $response->header( 'Cache-Control: private' );
660 return;
663 $useXVO = $config->get( 'UseXVO' );
664 if ( $this->mCacheMode == 'anon-public-user-private' ) {
665 $out->addVaryHeader( 'Cookie' );
666 $response->header( $out->getVaryHeader() );
667 if ( $useXVO ) {
668 $response->header( $out->getXVO() );
669 if ( $out->haveCacheVaryCookies() ) {
670 // Logged in, mark this request private
671 $response->header( 'Cache-Control: private' );
672 return;
674 // Logged out, send normal public headers below
675 } elseif ( session_id() != '' ) {
676 // Logged in or otherwise has session (e.g. anonymous users who have edited)
677 // Mark request private
678 $response->header( 'Cache-Control: private' );
680 return;
681 } // else no XVO and anonymous, send public headers below
684 // Send public headers
685 $response->header( $out->getVaryHeader() );
686 if ( $useXVO ) {
687 $response->header( $out->getXVO() );
690 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
691 if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
692 $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
694 if ( !isset( $this->mCacheControl['max-age'] ) ) {
695 $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
698 if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
699 // Public cache not requested
700 // Sending a Vary header in this case is harmless, and protects us
701 // against conditional calls of setCacheMaxAge().
702 $response->header( 'Cache-Control: private' );
704 return;
707 $this->mCacheControl['public'] = true;
709 // Send an Expires header
710 $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
711 $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
712 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
714 // Construct the Cache-Control header
715 $ccHeader = '';
716 $separator = '';
717 foreach ( $this->mCacheControl as $name => $value ) {
718 if ( is_bool( $value ) ) {
719 if ( $value ) {
720 $ccHeader .= $separator . $name;
721 $separator = ', ';
723 } else {
724 $ccHeader .= $separator . "$name=$value";
725 $separator = ', ';
729 $response->header( "Cache-Control: $ccHeader" );
733 * Replace the result data with the information about an exception.
734 * Returns the error code
735 * @param Exception $e
736 * @return string
738 protected function substituteResultWithError( $e ) {
739 $result = $this->getResult();
741 // Printer may not be initialized if the extractRequestParams() fails for the main module
742 if ( !isset( $this->mPrinter ) ) {
743 // The printer has not been created yet. Try to manually get formatter value.
744 $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
745 if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) {
746 $value = self::API_DEFAULT_FORMAT;
749 $this->mPrinter = $this->createPrinterByName( $value );
752 // Printer may not be able to handle errors. This is particularly
753 // likely if the module returns something for getCustomPrinter().
754 if ( !$this->mPrinter->canPrintErrors() ) {
755 $this->mPrinter->safeProfileOut();
756 $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT );
759 // Update raw mode flag for the selected printer.
760 $result->setRawMode( $this->mPrinter->getNeedsRawData() );
762 $config = $this->getConfig();
764 if ( $e instanceof UsageException ) {
765 // User entered incorrect parameters - generate error response
766 $errMessage = $e->getMessageArray();
767 $link = wfExpandUrl( wfScript( 'api' ) );
768 ApiResult::setContent( $errMessage, "See $link for API usage" );
769 } else {
770 // Something is seriously wrong
771 if ( ( $e instanceof DBQueryError ) && !$config->get( 'ShowSQLErrors' ) ) {
772 $info = 'Database query error';
773 } else {
774 $info = "Exception Caught: {$e->getMessage()}";
777 $errMessage = array(
778 'code' => 'internal_api_error_' . get_class( $e ),
779 'info' => '[' . MWExceptionHandler::getLogId( $e ) . '] ' . $info,
781 if ( $config->get( 'ShowExceptionDetails' ) ) {
782 ApiResult::setContent(
783 $errMessage,
784 MWExceptionHandler::getRedactedTraceAsString( $e )
789 // Remember all the warnings to re-add them later
790 $oldResult = $result->getData();
791 $warnings = isset( $oldResult['warnings'] ) ? $oldResult['warnings'] : null;
793 $result->reset();
794 // Re-add the id
795 $requestid = $this->getParameter( 'requestid' );
796 if ( !is_null( $requestid ) ) {
797 $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK );
799 if ( $config->get( 'ShowHostnames' ) ) {
800 // servedby is especially useful when debugging errors
801 $result->addValue( null, 'servedby', wfHostName(), ApiResult::NO_SIZE_CHECK );
803 if ( $warnings !== null ) {
804 $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK );
807 $result->addValue( null, 'error', $errMessage, ApiResult::NO_SIZE_CHECK );
809 return $errMessage['code'];
813 * Set up for the execution.
814 * @return array
816 protected function setupExecuteAction() {
817 // First add the id to the top element
818 $result = $this->getResult();
819 $requestid = $this->getParameter( 'requestid' );
820 if ( !is_null( $requestid ) ) {
821 $result->addValue( null, 'requestid', $requestid );
824 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
825 $servedby = $this->getParameter( 'servedby' );
826 if ( $servedby ) {
827 $result->addValue( null, 'servedby', wfHostName() );
831 if ( $this->getParameter( 'curtimestamp' ) ) {
832 $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601, time() ),
833 ApiResult::NO_SIZE_CHECK );
836 $params = $this->extractRequestParams();
838 $this->mAction = $params['action'];
840 if ( !is_string( $this->mAction ) ) {
841 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
844 return $params;
848 * Set up the module for response
849 * @return ApiBase The module that will handle this action
850 * @throws MWException
851 * @throws UsageException
853 protected function setupModule() {
854 // Instantiate the module requested by the user
855 $module = $this->mModuleMgr->getModule( $this->mAction, 'action' );
856 if ( $module === null ) {
857 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
859 $moduleParams = $module->extractRequestParams();
861 // Check token, if necessary
862 if ( $module->needsToken() === true ) {
863 throw new MWException(
864 "Module '{$module->getModuleName()}' must be updated for the new token handling. " .
865 "See documentation for ApiBase::needsToken for details."
868 if ( $module->needsToken() ) {
869 if ( !$module->mustBePosted() ) {
870 throw new MWException(
871 "Module '{$module->getModuleName()}' must require POST to use tokens."
875 if ( !isset( $moduleParams['token'] ) ) {
876 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
879 if ( !$this->getConfig()->get( 'DebugAPI' ) &&
880 array_key_exists(
881 $module->encodeParamName( 'token' ),
882 $this->getRequest()->getQueryValues()
885 $this->dieUsage(
886 "The '{$module->encodeParamName( 'token' )}' parameter was found in the query string, but must be in the POST body",
887 'mustposttoken'
891 if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) {
892 $this->dieUsageMsg( 'sessionfailure' );
896 return $module;
900 * Check the max lag if necessary
901 * @param ApiBase $module Api module being used
902 * @param array $params Array an array containing the request parameters.
903 * @return bool True on success, false should exit immediately
905 protected function checkMaxLag( $module, $params ) {
906 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
907 // Check for maxlag
908 $maxLag = $params['maxlag'];
909 list( $host, $lag ) = wfGetLB()->getMaxLag();
910 if ( $lag > $maxLag ) {
911 $response = $this->getRequest()->response();
913 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
914 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
916 if ( $this->getConfig()->get( 'ShowHostnames' ) ) {
917 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
920 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
924 return true;
928 * Check for sufficient permissions to execute
929 * @param ApiBase $module An Api module
931 protected function checkExecutePermissions( $module ) {
932 $user = $this->getUser();
933 if ( $module->isReadMode() && !User::isEveryoneAllowed( 'read' ) &&
934 !$user->isAllowed( 'read' )
936 $this->dieUsageMsg( 'readrequired' );
938 if ( $module->isWriteMode() ) {
939 if ( !$this->mEnableWrite ) {
940 $this->dieUsageMsg( 'writedisabled' );
942 if ( !$user->isAllowed( 'writeapi' ) ) {
943 $this->dieUsageMsg( 'writerequired' );
945 if ( wfReadOnly() ) {
946 $this->dieReadOnly();
950 // Allow extensions to stop execution for arbitrary reasons.
951 $message = false;
952 if ( !Hooks::run( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
953 $this->dieUsageMsg( $message );
958 * Check asserts of the user's rights
959 * @param array $params
961 protected function checkAsserts( $params ) {
962 if ( isset( $params['assert'] ) ) {
963 $user = $this->getUser();
964 switch ( $params['assert'] ) {
965 case 'user':
966 if ( $user->isAnon() ) {
967 $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' );
969 break;
970 case 'bot':
971 if ( !$user->isAllowed( 'bot' ) ) {
972 $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' );
974 break;
980 * Check POST for external response and setup result printer
981 * @param ApiBase $module An Api module
982 * @param array $params An array with the request parameters
984 protected function setupExternalResponse( $module, $params ) {
985 if ( !$this->getRequest()->wasPosted() && $module->mustBePosted() ) {
986 // Module requires POST. GET request might still be allowed
987 // if $wgDebugApi is true, otherwise fail.
988 $this->dieUsageMsgOrDebug( array( 'mustbeposted', $this->mAction ) );
991 // See if custom printer is used
992 $this->mPrinter = $module->getCustomPrinter();
993 if ( is_null( $this->mPrinter ) ) {
994 // Create an appropriate printer
995 $this->mPrinter = $this->createPrinterByName( $params['format'] );
998 if ( $this->mPrinter->getNeedsRawData() ) {
999 $this->getResult()->setRawMode();
1004 * Execute the actual module, without any error handling
1006 protected function executeAction() {
1007 $params = $this->setupExecuteAction();
1008 $module = $this->setupModule();
1009 $this->mModule = $module;
1011 $this->checkExecutePermissions( $module );
1013 if ( !$this->checkMaxLag( $module, $params ) ) {
1014 return;
1017 if ( !$this->mInternalMode ) {
1018 $this->setupExternalResponse( $module, $params );
1021 $this->checkAsserts( $params );
1023 // Execute
1024 $module->profileIn();
1025 $module->execute();
1026 Hooks::run( 'APIAfterExecute', array( &$module ) );
1027 $module->profileOut();
1029 $this->reportUnusedParams();
1031 if ( !$this->mInternalMode ) {
1032 //append Debug information
1033 MWDebug::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
1035 // Print result data
1036 $this->printResult( false );
1041 * Log the preceding request
1042 * @param int $time Time in seconds
1044 protected function logRequest( $time ) {
1045 $request = $this->getRequest();
1046 $milliseconds = $time === null ? '?' : round( $time * 1000 );
1047 $s = 'API' .
1048 ' ' . $request->getMethod() .
1049 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
1050 ' ' . $request->getIP() .
1051 ' T=' . $milliseconds . 'ms';
1052 foreach ( $this->getParamsUsed() as $name ) {
1053 $value = $request->getVal( $name );
1054 if ( $value === null ) {
1055 continue;
1057 $s .= ' ' . $name . '=';
1058 if ( strlen( $value ) > 256 ) {
1059 $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
1060 $s .= $encValue . '[...]';
1061 } else {
1062 $s .= $this->encodeRequestLogValue( $value );
1065 $s .= "\n";
1066 wfDebugLog( 'api', $s, 'private' );
1070 * Encode a value in a format suitable for a space-separated log line.
1071 * @param string $s
1072 * @return string
1074 protected function encodeRequestLogValue( $s ) {
1075 static $table;
1076 if ( !$table ) {
1077 $chars = ';@$!*(),/:';
1078 $numChars = strlen( $chars );
1079 for ( $i = 0; $i < $numChars; $i++ ) {
1080 $table[rawurlencode( $chars[$i] )] = $chars[$i];
1084 return strtr( rawurlencode( $s ), $table );
1088 * Get the request parameters used in the course of the preceding execute() request
1089 * @return array
1091 protected function getParamsUsed() {
1092 return array_keys( $this->mParamsUsed );
1096 * Get a request value, and register the fact that it was used, for logging.
1097 * @param string $name
1098 * @param mixed $default
1099 * @return mixed
1101 public function getVal( $name, $default = null ) {
1102 $this->mParamsUsed[$name] = true;
1104 $ret = $this->getRequest()->getVal( $name );
1105 if ( $ret === null ) {
1106 if ( $this->getRequest()->getArray( $name ) !== null ) {
1107 // See bug 10262 for why we don't just join( '|', ... ) the
1108 // array.
1109 $this->setWarning(
1110 "Parameter '$name' uses unsupported PHP array syntax"
1113 $ret = $default;
1115 return $ret;
1119 * Get a boolean request value, and register the fact that the parameter
1120 * was used, for logging.
1121 * @param string $name
1122 * @return bool
1124 public function getCheck( $name ) {
1125 return $this->getVal( $name, null ) !== null;
1129 * Get a request upload, and register the fact that it was used, for logging.
1131 * @since 1.21
1132 * @param string $name Parameter name
1133 * @return WebRequestUpload
1135 public function getUpload( $name ) {
1136 $this->mParamsUsed[$name] = true;
1138 return $this->getRequest()->getUpload( $name );
1142 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
1143 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
1145 protected function reportUnusedParams() {
1146 $paramsUsed = $this->getParamsUsed();
1147 $allParams = $this->getRequest()->getValueNames();
1149 if ( !$this->mInternalMode ) {
1150 // Printer has not yet executed; don't warn that its parameters are unused
1151 $printerParams = array_map(
1152 array( $this->mPrinter, 'encodeParamName' ),
1153 array_keys( $this->mPrinter->getFinalParams() ?: array() )
1155 $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams );
1156 } else {
1157 $unusedParams = array_diff( $allParams, $paramsUsed );
1160 if ( count( $unusedParams ) ) {
1161 $s = count( $unusedParams ) > 1 ? 's' : '';
1162 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
1167 * Print results using the current printer
1169 * @param bool $isError
1171 protected function printResult( $isError ) {
1172 if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) {
1173 $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' );
1176 $this->getResult()->cleanUpUTF8();
1177 $printer = $this->mPrinter;
1178 $printer->profileIn();
1180 $printer->initPrinter( false );
1182 $printer->execute();
1183 $printer->closePrinter();
1184 $printer->profileOut();
1188 * @return bool
1190 public function isReadMode() {
1191 return false;
1195 * See ApiBase for description.
1197 * @return array
1199 public function getAllowedParams() {
1200 return array(
1201 'action' => array(
1202 ApiBase::PARAM_DFLT => 'help',
1203 ApiBase::PARAM_TYPE => 'submodule',
1205 'format' => array(
1206 ApiBase::PARAM_DFLT => ApiMain::API_DEFAULT_FORMAT,
1207 ApiBase::PARAM_TYPE => 'submodule',
1209 'maxlag' => array(
1210 ApiBase::PARAM_TYPE => 'integer'
1212 'smaxage' => array(
1213 ApiBase::PARAM_TYPE => 'integer',
1214 ApiBase::PARAM_DFLT => 0
1216 'maxage' => array(
1217 ApiBase::PARAM_TYPE => 'integer',
1218 ApiBase::PARAM_DFLT => 0
1220 'assert' => array(
1221 ApiBase::PARAM_TYPE => array( 'user', 'bot' )
1223 'requestid' => null,
1224 'servedby' => false,
1225 'curtimestamp' => false,
1226 'origin' => null,
1227 'uselang' => array(
1228 ApiBase::PARAM_DFLT => 'user',
1233 /** @see ApiBase::getExamplesMessages() */
1234 protected function getExamplesMessages() {
1235 return array(
1236 'action=help'
1237 => 'apihelp-help-example-main',
1238 'action=help&recursivesubmodules=1'
1239 => 'apihelp-help-example-recursive',
1243 public function modifyHelp( array &$help, array $options ) {
1244 // Wish PHP had an "array_insert_before". Instead, we have to manually
1245 // reindex the array to get 'permissions' in the right place.
1246 $oldHelp = $help;
1247 $help = array();
1248 foreach ( $oldHelp as $k => $v ) {
1249 if ( $k === 'submodules' ) {
1250 $help['permissions'] = '';
1252 $help[$k] = $v;
1254 $help['credits'] = '';
1256 // Fill 'permissions'
1257 $help['permissions'] .= Html::openElement( 'div',
1258 array( 'class' => 'apihelp-block apihelp-permissions' ) );
1259 $m = $this->msg( 'api-help-permissions' );
1260 if ( !$m->isDisabled() ) {
1261 $help['permissions'] .= Html::rawElement( 'div', array( 'class' => 'apihelp-block-head' ),
1262 $m->numParams( count( self::$mRights ) )->parse()
1265 $help['permissions'] .= Html::openElement( 'dl' );
1266 foreach ( self::$mRights as $right => $rightMsg ) {
1267 $help['permissions'] .= Html::element( 'dt', null, $right );
1269 $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse();
1270 $help['permissions'] .= Html::rawElement( 'dd', null, $rightMsg );
1272 $groups = array_map( function ( $group ) {
1273 return $group == '*' ? 'all' : $group;
1274 }, User::getGroupsWithPermission( $right ) );
1276 $help['permissions'] .= Html::rawElement( 'dd', null,
1277 $this->msg( 'api-help-permissions-granted-to' )
1278 ->numParams( count( $groups ) )
1279 ->params( $this->getLanguage()->commaList( $groups ) )
1280 ->parse()
1283 $help['permissions'] .= Html::closeElement( 'dl' );
1284 $help['permissions'] .= Html::closeElement( 'div' );
1286 // Fill 'credits', if applicable
1287 if ( empty( $options['nolead'] ) ) {
1288 $help['credits'] .= Html::element( 'h' . min( 6, $options['headerlevel'] + 1 ),
1289 array( 'id' => '+credits', 'class' => 'apihelp-header' ),
1290 $this->msg( 'api-credits-header' )->parse()
1292 $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock();
1296 private $mCanApiHighLimits = null;
1299 * Check whether the current user is allowed to use high limits
1300 * @return bool
1302 public function canApiHighLimits() {
1303 if ( !isset( $this->mCanApiHighLimits ) ) {
1304 $this->mCanApiHighLimits = $this->getUser()->isAllowed( 'apihighlimits' );
1307 return $this->mCanApiHighLimits;
1311 * Overrides to return this instance's module manager.
1312 * @return ApiModuleManager
1314 public function getModuleManager() {
1315 return $this->mModuleMgr;
1319 * Fetches the user agent used for this request
1321 * The value will be the combination of the 'Api-User-Agent' header (if
1322 * any) and the standard User-Agent header (if any).
1324 * @return string
1326 public function getUserAgent() {
1327 return trim(
1328 $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' .
1329 $this->getRequest()->getHeader( 'User-agent' )
1333 /************************************************************************//**
1334 * @name Deprecated
1335 * @{
1339 * Sets whether the pretty-printer should format *bold* and $italics$
1341 * @deprecated since 1.25
1342 * @param bool $help
1344 public function setHelp( $help = true ) {
1345 wfDeprecated( __METHOD__, '1.25' );
1346 $this->mPrinter->setHelp( $help );
1350 * Override the parent to generate help messages for all available modules.
1352 * @deprecated since 1.25
1353 * @return string
1355 public function makeHelpMsg() {
1356 wfDeprecated( __METHOD__, '1.25' );
1357 global $wgMemc;
1358 $this->setHelp();
1359 // Get help text from cache if present
1360 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1361 str_replace( ' ', '_', SpecialVersion::getVersion( 'nodb' ) ) );
1363 $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' );
1364 if ( $cacheHelpTimeout > 0 ) {
1365 $cached = $wgMemc->get( $key );
1366 if ( $cached ) {
1367 return $cached;
1370 $retval = $this->reallyMakeHelpMsg();
1371 if ( $cacheHelpTimeout > 0 ) {
1372 $wgMemc->set( $key, $retval, $cacheHelpTimeout );
1375 return $retval;
1379 * @deprecated since 1.25
1380 * @return mixed|string
1382 public function reallyMakeHelpMsg() {
1383 wfDeprecated( __METHOD__, '1.25' );
1384 $this->setHelp();
1386 // Use parent to make default message for the main module
1387 $msg = parent::makeHelpMsg();
1389 $astriks = str_repeat( '*** ', 14 );
1390 $msg .= "\n\n$astriks Modules $astriks\n\n";
1392 foreach ( $this->mModuleMgr->getNames( 'action' ) as $name ) {
1393 $module = $this->mModuleMgr->getModule( $name );
1394 $msg .= self::makeHelpMsgHeader( $module, 'action' );
1396 $msg2 = $module->makeHelpMsg();
1397 if ( $msg2 !== false ) {
1398 $msg .= $msg2;
1400 $msg .= "\n";
1403 $msg .= "\n$astriks Permissions $astriks\n\n";
1404 foreach ( self::$mRights as $right => $rightMsg ) {
1405 $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )
1406 ->useDatabase( false )
1407 ->inLanguage( 'en' )
1408 ->text();
1409 $groups = User::getGroupsWithPermission( $right );
1410 $msg .= "* " . $right . " *\n $rightsMsg" .
1411 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1414 $msg .= "\n$astriks Formats $astriks\n\n";
1415 foreach ( $this->mModuleMgr->getNames( 'format' ) as $name ) {
1416 $module = $this->mModuleMgr->getModule( $name );
1417 $msg .= self::makeHelpMsgHeader( $module, 'format' );
1418 $msg2 = $module->makeHelpMsg();
1419 if ( $msg2 !== false ) {
1420 $msg .= $msg2;
1422 $msg .= "\n";
1425 $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text();
1426 $credits = str_replace( "\n", "\n ", $credits );
1427 $msg .= "\n*** Credits: ***\n $credits\n";
1429 return $msg;
1433 * @deprecated since 1.25
1434 * @param ApiBase $module
1435 * @param string $paramName What type of request is this? e.g. action,
1436 * query, list, prop, meta, format
1437 * @return string
1439 public static function makeHelpMsgHeader( $module, $paramName ) {
1440 wfDeprecated( __METHOD__, '1.25' );
1441 $modulePrefix = $module->getModulePrefix();
1442 if ( strval( $modulePrefix ) !== '' ) {
1443 $modulePrefix = "($modulePrefix) ";
1446 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1450 * Check whether the user wants us to show version information in the API help
1451 * @return bool
1452 * @deprecated since 1.21, always returns false
1454 public function getShowVersions() {
1455 wfDeprecated( __METHOD__, '1.21' );
1457 return false;
1461 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1462 * classes who wish to add their own modules to their lexicon or override the
1463 * behavior of inherent ones.
1465 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1466 * @param string $name The identifier for this module.
1467 * @param ApiBase $class The class where this module is implemented.
1469 protected function addModule( $name, $class ) {
1470 $this->getModuleManager()->addModule( $name, 'action', $class );
1474 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1475 * classes who wish to add to or modify current formatters.
1477 * @deprecated since 1.21, Use getModuleManager()->addModule() instead.
1478 * @param string $name The identifier for this format.
1479 * @param ApiFormatBase $class The class implementing this format.
1481 protected function addFormat( $name, $class ) {
1482 $this->getModuleManager()->addModule( $name, 'format', $class );
1486 * Get the array mapping module names to class names
1487 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1488 * @return array
1490 function getModules() {
1491 return $this->getModuleManager()->getNamesWithClasses( 'action' );
1495 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1497 * @since 1.18
1498 * @deprecated since 1.21, Use getModuleManager()'s methods instead.
1499 * @return array
1501 public function getFormats() {
1502 return $this->getModuleManager()->getNamesWithClasses( 'format' );
1505 /**@}*/
1510 * This exception will be thrown when dieUsage is called to stop module execution.
1512 * @ingroup API
1514 class UsageException extends MWException {
1516 private $mCodestr;
1519 * @var null|array
1521 private $mExtraData;
1524 * @param string $message
1525 * @param string $codestr
1526 * @param int $code
1527 * @param array|null $extradata
1529 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1530 parent::__construct( $message, $code );
1531 $this->mCodestr = $codestr;
1532 $this->mExtraData = $extradata;
1536 * @return string
1538 public function getCodeString() {
1539 return $this->mCodestr;
1543 * @return array
1545 public function getMessageArray() {
1546 $result = array(
1547 'code' => $this->mCodestr,
1548 'info' => $this->getMessage()
1550 if ( is_array( $this->mExtraData ) ) {
1551 $result = array_merge( $result, $this->mExtraData );
1554 return $result;
1558 * @return string
1560 public function __toString() {
1561 return "{$this->getCodeString()}: {$this->getMessage()}";
1566 * For really cool vim folding this needs to be at the end:
1567 * vim: foldmarker=@{,@} foldmethod=marker