Merge "Add missing wfProfileOut()"
[mediawiki.git] / includes / api / ApiMain.php
blob97f5ecd61ea0b4bbeeaa204d653343565e1b414b
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 {
43 /**
44 * When no format parameter is given, this format will be used
46 const API_DEFAULT_FORMAT = 'xmlfm';
48 /**
49 * List of available modules: action name => module class
51 private static $Modules = array(
52 'login' => 'ApiLogin',
53 'logout' => 'ApiLogout',
54 'query' => 'ApiQuery',
55 'expandtemplates' => 'ApiExpandTemplates',
56 'parse' => 'ApiParse',
57 'opensearch' => 'ApiOpenSearch',
58 'feedcontributions' => 'ApiFeedContributions',
59 'feedwatchlist' => 'ApiFeedWatchlist',
60 'help' => 'ApiHelp',
61 'paraminfo' => 'ApiParamInfo',
62 'rsd' => 'ApiRsd',
63 'compare' => 'ApiComparePages',
64 'tokens' => 'ApiTokens',
66 // Write modules
67 'purge' => 'ApiPurge',
68 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp',
69 'rollback' => 'ApiRollback',
70 'delete' => 'ApiDelete',
71 'undelete' => 'ApiUndelete',
72 'protect' => 'ApiProtect',
73 'block' => 'ApiBlock',
74 'unblock' => 'ApiUnblock',
75 'move' => 'ApiMove',
76 'edit' => 'ApiEditPage',
77 'upload' => 'ApiUpload',
78 'filerevert' => 'ApiFileRevert',
79 'emailuser' => 'ApiEmailUser',
80 'watch' => 'ApiWatch',
81 'patrol' => 'ApiPatrol',
82 'import' => 'ApiImport',
83 'userrights' => 'ApiUserrights',
84 'options' => 'ApiOptions',
87 /**
88 * List of available formats: format name => format class
90 private static $Formats = array(
91 'json' => 'ApiFormatJson',
92 'jsonfm' => 'ApiFormatJson',
93 'php' => 'ApiFormatPhp',
94 'phpfm' => 'ApiFormatPhp',
95 'wddx' => 'ApiFormatWddx',
96 'wddxfm' => 'ApiFormatWddx',
97 'xml' => 'ApiFormatXml',
98 'xmlfm' => 'ApiFormatXml',
99 'yaml' => 'ApiFormatYaml',
100 'yamlfm' => 'ApiFormatYaml',
101 'rawfm' => 'ApiFormatJson',
102 'txt' => 'ApiFormatTxt',
103 'txtfm' => 'ApiFormatTxt',
104 'dbg' => 'ApiFormatDbg',
105 'dbgfm' => 'ApiFormatDbg',
106 'dump' => 'ApiFormatDump',
107 'dumpfm' => 'ApiFormatDump',
108 'none' => 'ApiFormatNone',
112 * List of user roles that are specifically relevant to the API.
113 * array( 'right' => array ( 'msg' => 'Some message with a $1',
114 * 'params' => array ( $someVarToSubst ) ),
115 * );
117 private static $mRights = array(
118 'writeapi' => array(
119 'msg' => 'Use of the write API',
120 'params' => array()
122 'apihighlimits' => array(
123 'msg' => 'Use higher limits in API queries (Slow queries: $1 results; Fast queries: $2 results). The limits for slow queries also apply to multivalue parameters.',
124 'params' => array( ApiBase::LIMIT_SML2, ApiBase::LIMIT_BIG2 )
129 * @var ApiFormatBase
131 private $mPrinter;
133 private $mModules, $mModuleNames, $mFormats, $mFormatNames;
134 private $mResult, $mAction, $mShowVersions, $mEnableWrite;
135 private $mInternalMode, $mSquidMaxage, $mModule;
137 private $mCacheMode = 'private';
138 private $mCacheControl = array();
139 private $mParamsUsed = array();
142 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
144 * @param $context IContextSource|WebRequest - if this is an instance of FauxRequest, errors are thrown and no printing occurs
145 * @param $enableWrite bool should be set to true if the api may modify data
147 public function __construct( $context = null, $enableWrite = false ) {
148 if ( $context === null ) {
149 $context = RequestContext::getMain();
150 } elseif ( $context instanceof WebRequest ) {
151 // BC for pre-1.19
152 $request = $context;
153 $context = RequestContext::getMain();
155 // We set a derivative context so we can change stuff later
156 $this->setContext( new DerivativeContext( $context ) );
158 if ( isset( $request ) ) {
159 $this->getContext()->setRequest( $request );
162 $this->mInternalMode = ( $this->getRequest() instanceof FauxRequest );
164 // Special handling for the main module: $parent === $this
165 parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
167 if ( !$this->mInternalMode ) {
168 // Impose module restrictions.
169 // If the current user cannot read,
170 // Remove all modules other than login
171 global $wgUser;
173 if ( $this->getVal( 'callback' ) !== null ) {
174 // JSON callback allows cross-site reads.
175 // For safety, strip user credentials.
176 wfDebug( "API: stripping user credentials for JSON callback\n" );
177 $wgUser = new User();
178 $this->getContext()->setUser( $wgUser );
182 global $wgAPIModules; // extension modules
183 $this->mModules = $wgAPIModules + self::$Modules;
185 $this->mModuleNames = array_keys( $this->mModules );
186 $this->mFormats = self::$Formats;
187 $this->mFormatNames = array_keys( $this->mFormats );
189 $this->mResult = new ApiResult( $this );
190 $this->mShowVersions = false;
191 $this->mEnableWrite = $enableWrite;
193 $this->mSquidMaxage = - 1; // flag for executeActionWithErrorHandling()
194 $this->mCommit = false;
198 * Return true if the API was started by other PHP code using FauxRequest
199 * @return bool
201 public function isInternalMode() {
202 return $this->mInternalMode;
206 * Get the ApiResult object associated with current request
208 * @return ApiResult
210 public function getResult() {
211 return $this->mResult;
215 * Get the API module object. Only works after executeAction()
217 * @return ApiBase
219 public function getModule() {
220 return $this->mModule;
224 * Get the result formatter object. Only works after setupExecuteAction()
226 * @return ApiFormatBase
228 public function getPrinter() {
229 return $this->mPrinter;
233 * Set how long the response should be cached.
235 * @param $maxage
237 public function setCacheMaxAge( $maxage ) {
238 $this->setCacheControl( array(
239 'max-age' => $maxage,
240 's-maxage' => $maxage
241 ) );
245 * Set the type of caching headers which will be sent.
247 * @param $mode String One of:
248 * - 'public': Cache this object in public caches, if the maxage or smaxage
249 * parameter is set, or if setCacheMaxAge() was called. If a maximum age is
250 * not provided by any of these means, the object will be private.
251 * - 'private': Cache this object only in private client-side caches.
252 * - 'anon-public-user-private': Make this object cacheable for logged-out
253 * users, but private for logged-in users. IMPORTANT: If this is set, it must be
254 * set consistently for a given URL, it cannot be set differently depending on
255 * things like the contents of the database, or whether the user is logged in.
257 * If the wiki does not allow anonymous users to read it, the mode set here
258 * will be ignored, and private caching headers will always be sent. In other words,
259 * the "public" mode is equivalent to saying that the data sent is as public as a page
260 * view.
262 * For user-dependent data, the private mode should generally be used. The
263 * anon-public-user-private mode should only be used where there is a particularly
264 * good performance reason for caching the anonymous response, but where the
265 * response to logged-in users may differ, or may contain private data.
267 * If this function is never called, then the default will be the private mode.
269 public function setCacheMode( $mode ) {
270 if ( !in_array( $mode, array( 'private', 'public', 'anon-public-user-private' ) ) ) {
271 wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" );
272 // Ignore for forwards-compatibility
273 return;
276 if ( !in_array( 'read', User::getGroupPermissions( array( '*' ) ), true ) ) {
277 // Private wiki, only private headers
278 if ( $mode !== 'private' ) {
279 wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" );
280 return;
284 wfDebug( __METHOD__ . ": setting cache mode $mode\n" );
285 $this->mCacheMode = $mode;
289 * @deprecated since 1.17 Private caching is now the default, so there is usually no
290 * need to call this function. If there is a need, you can use
291 * $this->setCacheMode('private')
293 public function setCachePrivate() {
294 wfDeprecated( __METHOD__, '1.17' );
295 $this->setCacheMode( 'private' );
299 * Set directives (key/value pairs) for the Cache-Control header.
300 * Boolean values will be formatted as such, by including or omitting
301 * without an equals sign.
303 * Cache control values set here will only be used if the cache mode is not
304 * private, see setCacheMode().
306 * @param $directives array
308 public function setCacheControl( $directives ) {
309 $this->mCacheControl = $directives + $this->mCacheControl;
313 * Make sure Vary: Cookie and friends are set. Use this when the output of a request
314 * may be cached for anons but may not be cached for logged-in users.
316 * WARNING: This function must be called CONSISTENTLY for a given URL. This means that a
317 * given URL must either always or never call this function; if it sometimes does and
318 * sometimes doesn't, stuff will break.
320 * @deprecated since 1.17 Use setCacheMode( 'anon-public-user-private' )
322 public function setVaryCookie() {
323 wfDeprecated( __METHOD__, '1.17' );
324 $this->setCacheMode( 'anon-public-user-private' );
328 * Create an instance of an output formatter by its name
330 * @param $format string
332 * @return ApiFormatBase
334 public function createPrinterByName( $format ) {
335 if ( !isset( $this->mFormats[$format] ) ) {
336 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
338 return new $this->mFormats[$format] ( $this, $format );
342 * Execute api request. Any errors will be handled if the API was called by the remote client.
344 public function execute() {
345 $this->profileIn();
346 if ( $this->mInternalMode ) {
347 $this->executeAction();
348 } else {
349 $this->executeActionWithErrorHandling();
352 $this->profileOut();
356 * Execute an action, and in case of an error, erase whatever partial results
357 * have been accumulated, and replace it with an error message and a help screen.
359 protected function executeActionWithErrorHandling() {
360 // Verify the CORS header before executing the action
361 if ( !$this->handleCORS() ) {
362 // handleCORS() has sent a 403, abort
363 return;
366 // In case an error occurs during data output,
367 // clear the output buffer and print just the error information
368 ob_start();
370 $t = microtime( true );
371 try {
372 $this->executeAction();
373 } catch ( Exception $e ) {
374 // Allow extra cleanup and logging
375 wfRunHooks( 'ApiMain::onException', array( $this, $e ) );
377 // Log it
378 if ( !( $e instanceof UsageException ) ) {
379 global $wgLogExceptionBacktrace;
380 if ( $wgLogExceptionBacktrace ) {
381 wfDebugLog( 'exception', $e->getLogMessage() . "\n" . $e->getTraceAsString() . "\n" );
382 } else {
383 wfDebugLog( 'exception', $e->getLogMessage() );
387 // Handle any kind of exception by outputing properly formatted error message.
388 // If this fails, an unhandled exception should be thrown so that global error
389 // handler will process and log it.
391 $errCode = $this->substituteResultWithError( $e );
393 // Error results should not be cached
394 $this->setCacheMode( 'private' );
396 $response = $this->getRequest()->response();
397 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
398 if ( $e->getCode() === 0 ) {
399 $response->header( $headerStr );
400 } else {
401 $response->header( $headerStr, true, $e->getCode() );
404 // Reset and print just the error message
405 ob_clean();
407 // If the error occurred during printing, do a printer->profileOut()
408 $this->mPrinter->safeProfileOut();
409 $this->printResult( true );
412 // Log the request whether or not there was an error
413 $this->logRequest( microtime( true ) - $t);
415 // Send cache headers after any code which might generate an error, to
416 // avoid sending public cache headers for errors.
417 $this->sendCacheHeaders();
419 if ( $this->mPrinter->getIsHtml() && !$this->mPrinter->isDisabled() ) {
420 echo wfReportTime();
423 ob_end_flush();
427 * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
429 * If no origin parameter is present, nothing happens.
430 * If an origin parameter is present but doesn't match the Origin header, a 403 status code
431 * is set and false is returned.
432 * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
433 * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
434 * headers are set.
436 * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
438 protected function handleCORS() {
439 global $wgCrossSiteAJAXdomains, $wgCrossSiteAJAXdomainExceptions;
441 $originParam = $this->getParameter( 'origin' ); // defaults to null
442 if ( $originParam === null ) {
443 // No origin parameter, nothing to do
444 return true;
447 $request = $this->getRequest();
448 $response = $request->response();
449 // Origin: header is a space-separated list of origins, check all of them
450 $originHeader = $request->getHeader( 'Origin' );
451 if ( $originHeader === false ) {
452 $origins = array();
453 } else {
454 $origins = explode( ' ', $originHeader );
456 if ( !in_array( $originParam, $origins ) ) {
457 // origin parameter set but incorrect
458 // Send a 403 response
459 $message = HttpStatus::getMessage( 403 );
460 $response->header( "HTTP/1.1 403 $message", true, 403 );
461 $response->header( 'Cache-Control: no-cache' );
462 echo "'origin' parameter does not match Origin header\n";
463 return false;
465 if ( self::matchOrigin( $originParam, $wgCrossSiteAJAXdomains, $wgCrossSiteAJAXdomainExceptions ) ) {
466 $response->header( "Access-Control-Allow-Origin: $originParam" );
467 $response->header( 'Access-Control-Allow-Credentials: true' );
468 $this->getOutput()->addVaryHeader( 'Origin' );
470 return true;
474 * Attempt to match an Origin header against a set of rules and a set of exceptions
475 * @param $value string Origin header
476 * @param $rules array Set of wildcard rules
477 * @param $exceptions array Set of wildcard rules
478 * @return bool True if $value matches a rule in $rules and doesn't match any rules in $exceptions, false otherwise
480 protected static function matchOrigin( $value, $rules, $exceptions ) {
481 foreach ( $rules as $rule ) {
482 if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
483 // Rule matches, check exceptions
484 foreach ( $exceptions as $exc ) {
485 if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
486 return false;
489 return true;
492 return false;
496 * Helper function to convert wildcard string into a regex
497 * '*' => '.*?'
498 * '?' => '.'
500 * @param $wildcard string String with wildcards
501 * @return string Regular expression
503 protected static function wildcardToRegex( $wildcard ) {
504 $wildcard = preg_quote( $wildcard, '/' );
505 $wildcard = str_replace(
506 array( '\*', '\?' ),
507 array( '.*?', '.' ),
508 $wildcard
510 return "/https?:\/\/$wildcard/";
513 protected function sendCacheHeaders() {
514 global $wgUseXVO, $wgVaryOnXFP;
515 $response = $this->getRequest()->response();
516 $out = $this->getOutput();
518 if ( $wgVaryOnXFP ) {
519 $out->addVaryHeader( 'X-Forwarded-Proto' );
522 if ( $this->mCacheMode == 'private' ) {
523 $response->header( 'Cache-Control: private' );
524 return;
527 if ( $this->mCacheMode == 'anon-public-user-private' ) {
528 $out->addVaryHeader( 'Cookie' );
529 $response->header( $out->getVaryHeader() );
530 if ( $wgUseXVO ) {
531 $response->header( $out->getXVO() );
532 if ( $out->haveCacheVaryCookies() ) {
533 // Logged in, mark this request private
534 $response->header( 'Cache-Control: private' );
535 return;
537 // Logged out, send normal public headers below
538 } elseif ( session_id() != '' ) {
539 // Logged in or otherwise has session (e.g. anonymous users who have edited)
540 // Mark request private
541 $response->header( 'Cache-Control: private' );
542 return;
543 } // else no XVO and anonymous, send public headers below
546 // Send public headers
547 $response->header( $out->getVaryHeader() );
548 if ( $wgUseXVO ) {
549 $response->header( $out->getXVO() );
552 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
553 if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
554 $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
556 if ( !isset( $this->mCacheControl['max-age'] ) ) {
557 $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
560 if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) {
561 // Public cache not requested
562 // Sending a Vary header in this case is harmless, and protects us
563 // against conditional calls of setCacheMaxAge().
564 $response->header( 'Cache-Control: private' );
565 return;
568 $this->mCacheControl['public'] = true;
570 // Send an Expires header
571 $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
572 $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge );
573 $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) );
575 // Construct the Cache-Control header
576 $ccHeader = '';
577 $separator = '';
578 foreach ( $this->mCacheControl as $name => $value ) {
579 if ( is_bool( $value ) ) {
580 if ( $value ) {
581 $ccHeader .= $separator . $name;
582 $separator = ', ';
584 } else {
585 $ccHeader .= $separator . "$name=$value";
586 $separator = ', ';
590 $response->header( "Cache-Control: $ccHeader" );
594 * Replace the result data with the information about an exception.
595 * Returns the error code
596 * @param $e Exception
597 * @return string
599 protected function substituteResultWithError( $e ) {
600 global $wgShowHostnames;
602 $result = $this->getResult();
603 // Printer may not be initialized if the extractRequestParams() fails for the main module
604 if ( !isset ( $this->mPrinter ) ) {
605 // The printer has not been created yet. Try to manually get formatter value.
606 $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
607 if ( !in_array( $value, $this->mFormatNames ) ) {
608 $value = self::API_DEFAULT_FORMAT;
611 $this->mPrinter = $this->createPrinterByName( $value );
612 if ( $this->mPrinter->getNeedsRawData() ) {
613 $result->setRawMode();
617 if ( $e instanceof UsageException ) {
618 // User entered incorrect parameters - print usage screen
619 $errMessage = $e->getMessageArray();
621 // Only print the help message when this is for the developer, not runtime
622 if ( $this->mPrinter->getWantsHelp() || $this->mAction == 'help' ) {
623 ApiResult::setContent( $errMessage, $this->makeHelpMsg() );
626 } else {
627 global $wgShowSQLErrors, $wgShowExceptionDetails;
628 // Something is seriously wrong
629 if ( ( $e instanceof DBQueryError ) && !$wgShowSQLErrors ) {
630 $info = 'Database query error';
631 } else {
632 $info = "Exception Caught: {$e->getMessage()}";
635 $errMessage = array(
636 'code' => 'internal_api_error_' . get_class( $e ),
637 'info' => $info,
639 ApiResult::setContent( $errMessage, $wgShowExceptionDetails ? "\n\n{$e->getTraceAsString()}\n\n" : '' );
642 $result->reset();
643 $result->disableSizeCheck();
644 // Re-add the id
645 $requestid = $this->getParameter( 'requestid' );
646 if ( !is_null( $requestid ) ) {
647 $result->addValue( null, 'requestid', $requestid );
650 if ( $wgShowHostnames ) {
651 // servedby is especially useful when debugging errors
652 $result->addValue( null, 'servedby', wfHostName() );
655 $result->addValue( null, 'error', $errMessage );
657 return $errMessage['code'];
661 * Set up for the execution.
662 * @return array
664 protected function setupExecuteAction() {
665 global $wgShowHostnames;
667 // First add the id to the top element
668 $result = $this->getResult();
669 $requestid = $this->getParameter( 'requestid' );
670 if ( !is_null( $requestid ) ) {
671 $result->addValue( null, 'requestid', $requestid );
674 if ( $wgShowHostnames ) {
675 $servedby = $this->getParameter( 'servedby' );
676 if ( $servedby ) {
677 $result->addValue( null, 'servedby', wfHostName() );
681 $params = $this->extractRequestParams();
683 $this->mShowVersions = $params['version'];
684 $this->mAction = $params['action'];
686 if ( !is_string( $this->mAction ) ) {
687 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
690 return $params;
694 * Set up the module for response
695 * @return ApiBase The module that will handle this action
697 protected function setupModule() {
698 // Instantiate the module requested by the user
699 $module = new $this->mModules[$this->mAction] ( $this, $this->mAction );
700 $this->mModule = $module;
702 $moduleParams = $module->extractRequestParams();
704 // Die if token required, but not provided (unless there is a gettoken parameter)
705 if ( isset( $moduleParams['gettoken'] ) ) {
706 $gettoken = $moduleParams['gettoken'];
707 } else {
708 $gettoken = false;
711 $salt = $module->getTokenSalt();
712 if ( $salt !== false && !$gettoken ) {
713 if ( !isset( $moduleParams['token'] ) ) {
714 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
715 } else {
716 if ( !$this->getUser()->matchEditToken( $moduleParams['token'], $salt, $this->getContext()->getRequest() ) ) {
717 $this->dieUsageMsg( 'sessionfailure' );
721 return $module;
725 * Check the max lag if necessary
726 * @param $module ApiBase object: Api module being used
727 * @param $params Array an array containing the request parameters.
728 * @return boolean True on success, false should exit immediately
730 protected function checkMaxLag( $module, $params ) {
731 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
732 // Check for maxlag
733 global $wgShowHostnames;
734 $maxLag = $params['maxlag'];
735 list( $host, $lag ) = wfGetLB()->getMaxLag();
736 if ( $lag > $maxLag ) {
737 $response = $this->getRequest()->response();
739 $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
740 $response->header( 'X-Database-Lag: ' . intval( $lag ) );
742 if ( $wgShowHostnames ) {
743 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
744 } else {
745 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
747 return false;
750 return true;
754 * Check for sufficient permissions to execute
755 * @param $module ApiBase An Api module
757 protected function checkExecutePermissions( $module ) {
758 $user = $this->getUser();
759 if ( $module->isReadMode() && !in_array( 'read', User::getGroupPermissions( array( '*' ) ), true ) &&
760 !$user->isAllowed( 'read' ) )
762 $this->dieUsageMsg( 'readrequired' );
764 if ( $module->isWriteMode() ) {
765 if ( !$this->mEnableWrite ) {
766 $this->dieUsageMsg( 'writedisabled' );
768 if ( !$user->isAllowed( 'writeapi' ) ) {
769 $this->dieUsageMsg( 'writerequired' );
771 if ( wfReadOnly() ) {
772 $this->dieReadOnly();
776 // Allow extensions to stop execution for arbitrary reasons.
777 $message = false;
778 if( !wfRunHooks( 'ApiCheckCanExecute', array( $module, $user, &$message ) ) ) {
779 $this->dieUsageMsg( $message );
784 * Check POST for external response and setup result printer
785 * @param $module ApiBase An Api module
786 * @param $params Array an array with the request parameters
788 protected function setupExternalResponse( $module, $params ) {
789 // Ignore mustBePosted() for internal calls
790 if ( $module->mustBePosted() && !$this->getRequest()->wasPosted() ) {
791 $this->dieUsageMsg( array( 'mustbeposted', $this->mAction ) );
794 // See if custom printer is used
795 $this->mPrinter = $module->getCustomPrinter();
796 if ( is_null( $this->mPrinter ) ) {
797 // Create an appropriate printer
798 $this->mPrinter = $this->createPrinterByName( $params['format'] );
801 if ( $this->mPrinter->getNeedsRawData() ) {
802 $this->getResult()->setRawMode();
807 * Execute the actual module, without any error handling
809 protected function executeAction() {
810 $params = $this->setupExecuteAction();
811 $module = $this->setupModule();
813 $this->checkExecutePermissions( $module );
815 if ( !$this->checkMaxLag( $module, $params ) ) {
816 return;
819 if ( !$this->mInternalMode ) {
820 $this->setupExternalResponse( $module, $params );
823 // Execute
824 $module->profileIn();
825 $module->execute();
826 wfRunHooks( 'APIAfterExecute', array( &$module ) );
827 $module->profileOut();
829 if ( !$this->mInternalMode ) {
830 // Report unused params
831 $this->reportUnusedParams();
833 //append Debug information
834 MWDebug::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() );
836 // Print result data
837 $this->printResult( false );
842 * Log the preceding request
843 * @param $time Time in seconds
845 protected function logRequest( $time ) {
846 $request = $this->getRequest();
847 $milliseconds = $time === null ? '?' : round( $time * 1000 );
848 $s = 'API' .
849 ' ' . $request->getMethod() .
850 ' ' . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) .
851 ' ' . $request->getIP() .
852 ' T=' . $milliseconds .'ms';
853 foreach ( $this->getParamsUsed() as $name ) {
854 $value = $request->getVal( $name );
855 if ( $value === null ) {
856 continue;
858 $s .= ' ' . $name . '=';
859 if ( strlen( $value ) > 256 ) {
860 $encValue = $this->encodeRequestLogValue( substr( $value, 0, 256 ) );
861 $s .= $encValue . '[...]';
862 } else {
863 $s .= $this->encodeRequestLogValue( $value );
866 $s .= "\n";
867 wfDebugLog( 'api', $s, false );
871 * Encode a value in a format suitable for a space-separated log line.
873 protected function encodeRequestLogValue( $s ) {
874 static $table;
875 if ( !$table ) {
876 $chars = ';@$!*(),/:';
877 for ( $i = 0; $i < strlen( $chars ); $i++ ) {
878 $table[ rawurlencode( $chars[$i] ) ] = $chars[$i];
881 return strtr( rawurlencode( $s ), $table );
885 * Get the request parameters used in the course of the preceding execute() request
887 protected function getParamsUsed() {
888 return array_keys( $this->mParamsUsed );
892 * Get a request value, and register the fact that it was used, for logging.
894 public function getVal( $name, $default = null ) {
895 $this->mParamsUsed[$name] = true;
896 return $this->getRequest()->getVal( $name, $default );
900 * Get a boolean request value, and register the fact that the parameter
901 * was used, for logging.
903 public function getCheck( $name ) {
904 $this->mParamsUsed[$name] = true;
905 return $this->getRequest()->getCheck( $name );
909 * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know,
910 * for example in case of spelling mistakes or a missing 'g' prefix for generators.
912 protected function reportUnusedParams() {
913 $paramsUsed = $this->getParamsUsed();
914 $allParams = $this->getRequest()->getValueNames();
916 $unusedParams = array_diff( $allParams, $paramsUsed );
917 if( count( $unusedParams ) ) {
918 $s = count( $unusedParams ) > 1 ? 's' : '';
919 $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" );
924 * Print results using the current printer
926 * @param $isError bool
928 protected function printResult( $isError ) {
929 $this->getResult()->cleanUpUTF8();
930 $printer = $this->mPrinter;
931 $printer->profileIn();
934 * If the help message is requested in the default (xmlfm) format,
935 * tell the printer not to escape ampersands so that our links do
936 * not break.
938 $printer->setUnescapeAmps( ( $this->mAction == 'help' || $isError )
939 && $printer->getFormat() == 'XML' && $printer->getIsHtml() );
941 $printer->initPrinter( $isError );
943 $printer->execute();
944 $printer->closePrinter();
945 $printer->profileOut();
949 * @return bool
951 public function isReadMode() {
952 return false;
956 * See ApiBase for description.
958 * @return array
960 public function getAllowedParams() {
961 return array(
962 'format' => array(
963 ApiBase::PARAM_DFLT => ApiMain::API_DEFAULT_FORMAT,
964 ApiBase::PARAM_TYPE => $this->mFormatNames
966 'action' => array(
967 ApiBase::PARAM_DFLT => 'help',
968 ApiBase::PARAM_TYPE => $this->mModuleNames
970 'version' => false,
971 'maxlag' => array(
972 ApiBase::PARAM_TYPE => 'integer'
974 'smaxage' => array(
975 ApiBase::PARAM_TYPE => 'integer',
976 ApiBase::PARAM_DFLT => 0
978 'maxage' => array(
979 ApiBase::PARAM_TYPE => 'integer',
980 ApiBase::PARAM_DFLT => 0
982 'requestid' => null,
983 'servedby' => false,
984 'origin' => null,
989 * See ApiBase for description.
991 * @return array
993 public function getParamDescription() {
994 return array(
995 'format' => 'The format of the output',
996 'action' => 'What action you would like to perform. See below for module help',
997 'version' => 'When showing help, include version for each module',
998 'maxlag' => array(
999 'Maximum lag can be used when MediaWiki is installed on a database replicated cluster.',
1000 'To save actions causing any more site replication lag, this parameter can make the client',
1001 'wait until the replication lag is less than the specified value.',
1002 'In case of a replag error, error code "maxlag" is returned, with the message like',
1003 '"Waiting for $host: $lag seconds lagged\n".',
1004 'See https://www.mediawiki.org/wiki/Manual:Maxlag_parameter for more information',
1006 'smaxage' => 'Set the s-maxage header to this many seconds. Errors are never cached',
1007 'maxage' => 'Set the max-age header to this many seconds. Errors are never cached',
1008 'requestid' => 'Request ID to distinguish requests. This will just be output back to you',
1009 'servedby' => 'Include the hostname that served the request in the results. Unconditionally shown on error',
1010 'origin' => array(
1011 'When accessing the API using a cross-domain AJAX request (CORS), set this to the originating domain.',
1012 'This must match one of the origins in the Origin: header exactly, so it has to be set to something like http://en.wikipedia.org or https://meta.wikimedia.org .',
1013 'If this parameter does not match the Origin: header, a 403 response will be returned.',
1014 'If this parameter matches the Origin: header and the origin is whitelisted, an Access-Control-Allow-Origin header will be set.',
1020 * See ApiBase for description.
1022 * @return array
1024 public function getDescription() {
1025 return array(
1028 '**********************************************************************************************************',
1029 '** **',
1030 '** This is an auto-generated MediaWiki API documentation page **',
1031 '** **',
1032 '** Documentation and Examples: **',
1033 '** https://www.mediawiki.org/wiki/API **',
1034 '** **',
1035 '**********************************************************************************************************',
1037 'Status: All features shown on this page should be working, but the API',
1038 ' is still in active development, and may change at any time.',
1039 ' Make sure to monitor our mailing list for any updates',
1041 'Erroneous requests: When erroneous requests are sent to the API, a HTTP header will be sent',
1042 ' with the key "MediaWiki-API-Error" and then both the value of the',
1043 ' header and the error code sent back will be set to the same value',
1045 ' In the case of an invalid action being passed, these will have a value',
1046 ' of "unknown_action"',
1048 ' For more information see https://www.mediawiki.org/wiki/API:Errors_and_warnings',
1050 'Documentation: https://www.mediawiki.org/wiki/API:Main_page',
1051 'FAQ https://www.mediawiki.org/wiki/API:FAQ',
1052 'Mailing list: https://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
1053 'Api Announcements: https://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce',
1054 'Bugs & Requests: https://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
1064 * @return array
1066 public function getPossibleErrors() {
1067 return array_merge( parent::getPossibleErrors(), array(
1068 array( 'readonlytext' ),
1069 array( 'code' => 'unknown_format', 'info' => 'Unrecognized format: format' ),
1070 array( 'code' => 'unknown_action', 'info' => 'The API requires a valid action parameter' ),
1071 array( 'code' => 'maxlag', 'info' => 'Waiting for host: x seconds lagged' ),
1072 array( 'code' => 'maxlag', 'info' => 'Waiting for a database server: x seconds lagged' ),
1073 ) );
1077 * Returns an array of strings with credits for the API
1078 * @return array
1080 protected function getCredits() {
1081 return array(
1082 'API developers:',
1083 ' Roan Kattouw "<Firstname>.<Lastname>@gmail.com" (lead developer Sep 2007-present)',
1084 ' Victor Vasiliev - vasilvv at gee mail dot com',
1085 ' Bryan Tong Minh - bryan . tongminh @ gmail . com',
1086 ' Sam Reed - sam @ reedyboy . net',
1087 ' Yuri Astrakhan "<Firstname><Lastname>@gmail.com" (creator, lead developer Sep 2006-Sep 2007)',
1089 'Please send your comments, suggestions and questions to mediawiki-api@lists.wikimedia.org',
1090 'or file a bug report at https://bugzilla.wikimedia.org/'
1095 * Sets whether the pretty-printer should format *bold* and $italics$
1097 * @param $help bool
1099 public function setHelp( $help = true ) {
1100 $this->mPrinter->setHelp( $help );
1104 * Override the parent to generate help messages for all available modules.
1106 * @return string
1108 public function makeHelpMsg() {
1109 global $wgMemc, $wgAPICacheHelpTimeout;
1110 $this->setHelp();
1111 // Get help text from cache if present
1112 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
1113 SpecialVersion::getVersion( 'nodb' ) .
1114 $this->getShowVersions() );
1115 if ( $wgAPICacheHelpTimeout > 0 ) {
1116 $cached = $wgMemc->get( $key );
1117 if ( $cached ) {
1118 return $cached;
1121 $retval = $this->reallyMakeHelpMsg();
1122 if ( $wgAPICacheHelpTimeout > 0 ) {
1123 $wgMemc->set( $key, $retval, $wgAPICacheHelpTimeout );
1125 return $retval;
1129 * @return mixed|string
1131 public function reallyMakeHelpMsg() {
1132 $this->setHelp();
1134 // Use parent to make default message for the main module
1135 $msg = parent::makeHelpMsg();
1137 $astriks = str_repeat( '*** ', 14 );
1138 $msg .= "\n\n$astriks Modules $astriks\n\n";
1139 foreach ( array_keys( $this->mModules ) as $moduleName ) {
1140 $module = new $this->mModules[$moduleName] ( $this, $moduleName );
1141 $msg .= self::makeHelpMsgHeader( $module, 'action' );
1142 $msg2 = $module->makeHelpMsg();
1143 if ( $msg2 !== false ) {
1144 $msg .= $msg2;
1146 $msg .= "\n";
1149 $msg .= "\n$astriks Permissions $astriks\n\n";
1150 foreach ( self::$mRights as $right => $rightMsg ) {
1151 $groups = User::getGroupsWithPermission( $right );
1152 $msg .= "* " . $right . " *\n " . wfMsgReplaceArgs( $rightMsg[ 'msg' ], $rightMsg[ 'params' ] ) .
1153 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n";
1157 $msg .= "\n$astriks Formats $astriks\n\n";
1158 foreach ( array_keys( $this->mFormats ) as $formatName ) {
1159 $module = $this->createPrinterByName( $formatName );
1160 $msg .= self::makeHelpMsgHeader( $module, 'format' );
1161 $msg2 = $module->makeHelpMsg();
1162 if ( $msg2 !== false ) {
1163 $msg .= $msg2;
1165 $msg .= "\n";
1168 $msg .= "\n*** Credits: ***\n " . implode( "\n ", $this->getCredits() ) . "\n";
1170 return $msg;
1174 * @param $module ApiBase
1175 * @param $paramName String What type of request is this? e.g. action, query, list, prop, meta, format
1176 * @return string
1178 public static function makeHelpMsgHeader( $module, $paramName ) {
1179 $modulePrefix = $module->getModulePrefix();
1180 if ( strval( $modulePrefix ) !== '' ) {
1181 $modulePrefix = "($modulePrefix) ";
1184 return "* $paramName={$module->getModuleName()} $modulePrefix*";
1187 private $mCanApiHighLimits = null;
1190 * Check whether the current user is allowed to use high limits
1191 * @return bool
1193 public function canApiHighLimits() {
1194 if ( !isset( $this->mCanApiHighLimits ) ) {
1195 $this->mCanApiHighLimits = $this->getUser()->isAllowed( 'apihighlimits' );
1198 return $this->mCanApiHighLimits;
1202 * Check whether the user wants us to show version information in the API help
1203 * @return bool
1205 public function getShowVersions() {
1206 return $this->mShowVersions;
1210 * Returns the version information of this file, plus it includes
1211 * the versions for all files that are not callable proper API modules
1213 * @return array
1215 public function getVersion() {
1216 $vers = array();
1217 $vers[] = 'MediaWiki: ' . SpecialVersion::getVersion() . "\n https://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/";
1218 $vers[] = __CLASS__ . ': $Id$';
1219 $vers[] = ApiBase::getBaseVersion();
1220 $vers[] = ApiFormatBase::getBaseVersion();
1221 $vers[] = ApiQueryBase::getBaseVersion();
1222 return $vers;
1226 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
1227 * classes who wish to add their own modules to their lexicon or override the
1228 * behavior of inherent ones.
1230 * @param $mdlName String The identifier for this module.
1231 * @param $mdlClass String The class where this module is implemented.
1233 protected function addModule( $mdlName, $mdlClass ) {
1234 $this->mModules[$mdlName] = $mdlClass;
1238 * Add or overwrite an output format for this ApiMain. Intended for use by extending
1239 * classes who wish to add to or modify current formatters.
1241 * @param $fmtName string The identifier for this format.
1242 * @param $fmtClass ApiFormatBase The class implementing this format.
1244 protected function addFormat( $fmtName, $fmtClass ) {
1245 $this->mFormats[$fmtName] = $fmtClass;
1249 * Get the array mapping module names to class names
1250 * @return array
1252 function getModules() {
1253 return $this->mModules;
1257 * Returns the list of supported formats in form ( 'format' => 'ClassName' )
1259 * @since 1.18
1260 * @return array
1262 public function getFormats() {
1263 return $this->mFormats;
1268 * This exception will be thrown when dieUsage is called to stop module execution.
1269 * The exception handling code will print a help screen explaining how this API may be used.
1271 * @ingroup API
1273 class UsageException extends MWException {
1275 private $mCodestr;
1278 * @var null|array
1280 private $mExtraData;
1283 * @param $message string
1284 * @param $codestr string
1285 * @param $code int
1286 * @param $extradata array|null
1288 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
1289 parent::__construct( $message, $code );
1290 $this->mCodestr = $codestr;
1291 $this->mExtraData = $extradata;
1295 * @return string
1297 public function getCodeString() {
1298 return $this->mCodestr;
1302 * @return array
1304 public function getMessageArray() {
1305 $result = array(
1306 'code' => $this->mCodestr,
1307 'info' => $this->getMessage()
1309 if ( is_array( $this->mExtraData ) ) {
1310 $result = array_merge( $result, $this->mExtraData );
1312 return $result;
1316 * @return string
1318 public function __toString() {
1319 return "{$this->getCodeString()}: {$this->getMessage()}";