* (bug 20049) Fixed in PHP notice in search highlighter that occurs in some cases
[mediawiki.git] / includes / api / ApiMain.php
blob35ddeca5ca07a5d8a0afca6a859592fb8b36433f
1 <?php
3 /**
4 * Created on Sep 4, 2006
6 * API for MediaWiki 1.8+
8 * Copyright © 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 * http://www.gnu.org/copyleft/gpl.html
26 if ( !defined( 'MEDIAWIKI' ) ) {
27 // Eclipse helper - will be ignored in production
28 require_once( 'ApiBase.php' );
31 /**
32 * @defgroup API API
35 /**
36 * This is the main API class, used for both external and internal processing.
37 * When executed, it will create the requested formatter object,
38 * instantiate and execute an object associated with the needed action,
39 * and use formatter to print results.
40 * In case of an exception, an error message will be printed using the same formatter.
42 * To use API from another application, run it using FauxRequest object, in which
43 * case any internal exceptions will not be handled but passed up to the caller.
44 * After successful execution, use getResult() for the resulting data.
46 * @ingroup API
48 class ApiMain extends ApiBase {
50 /**
51 * When no format parameter is given, this format will be used
53 const API_DEFAULT_FORMAT = 'xmlfm';
55 /**
56 * List of available modules: action name => module class
58 private static $Modules = array(
59 'login' => 'ApiLogin',
60 'logout' => 'ApiLogout',
61 'query' => 'ApiQuery',
62 'expandtemplates' => 'ApiExpandTemplates',
63 'parse' => 'ApiParse',
64 'opensearch' => 'ApiOpenSearch',
65 'feedwatchlist' => 'ApiFeedWatchlist',
66 'go' => 'ApiGo',
67 'help' => 'ApiHelp',
68 'paraminfo' => 'ApiParamInfo',
70 // Write modules
71 'purge' => 'ApiPurge',
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 'emailuser' => 'ApiEmailUser',
82 'watch' => 'ApiWatch',
83 'patrol' => 'ApiPatrol',
84 'import' => 'ApiImport',
85 'userrights' => 'ApiUserrights',
88 /**
89 * List of available formats: format name => format class
91 private static $Formats = array(
92 'json' => 'ApiFormatJson',
93 'jsonfm' => 'ApiFormatJson',
94 'php' => 'ApiFormatPhp',
95 'phpfm' => 'ApiFormatPhp',
96 'wddx' => 'ApiFormatWddx',
97 'wddxfm' => 'ApiFormatWddx',
98 'xml' => 'ApiFormatXml',
99 'xmlfm' => 'ApiFormatXml',
100 'yaml' => 'ApiFormatYaml',
101 'yamlfm' => 'ApiFormatYaml',
102 'rawfm' => 'ApiFormatJson',
103 'txt' => 'ApiFormatTxt',
104 'txtfm' => 'ApiFormatTxt',
105 'dbg' => 'ApiFormatDbg',
106 'dbgfm' => 'ApiFormatDbg'
110 * List of user roles that are specifically relevant to the API.
111 * array( 'right' => array ( 'msg' => 'Some message with a $1',
112 * 'params' => array ( $someVarToSubst ) ),
113 * );
115 private static $mRights = array(
116 'writeapi' => array(
117 'msg' => 'Use of the write API',
118 'params' => array()
120 'apihighlimits' => array(
121 '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.',
122 'params' => array( ApiMain::LIMIT_SML2, ApiMain::LIMIT_BIG2 )
126 private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
127 private $mResult, $mAction, $mShowVersions, $mEnableWrite, $mRequest;
128 private $mInternalMode, $mSquidMaxage, $mModule;
130 private $mCacheControl = array( 'must-revalidate' => true );
133 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
135 * @param $request object - if this is an instance of FauxRequest, errors are thrown and no printing occurs
136 * @param $enableWrite bool should be set to true if the api may modify data
138 public function __construct( $request, $enableWrite = false ) {
139 $this->mInternalMode = ( $request instanceof FauxRequest );
141 // Special handling for the main module: $parent === $this
142 parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
144 if ( !$this->mInternalMode ) {
145 // Impose module restrictions.
146 // If the current user cannot read,
147 // Remove all modules other than login
148 global $wgUser;
150 if ( $request->getVal( 'callback' ) !== null ) {
151 // JSON callback allows cross-site reads.
152 // For safety, strip user credentials.
153 wfDebug( "API: stripping user credentials for JSON callback\n" );
154 $wgUser = new User();
158 global $wgAPIModules; // extension modules
159 $this->mModules = $wgAPIModules + self::$Modules;
161 $this->mModuleNames = array_keys( $this->mModules );
162 $this->mFormats = self::$Formats;
163 $this->mFormatNames = array_keys( $this->mFormats );
165 $this->mResult = new ApiResult( $this );
166 $this->mShowVersions = false;
167 $this->mEnableWrite = $enableWrite;
169 $this->mRequest = &$request;
171 $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling()
172 $this->mCommit = false;
176 * Return true if the API was started by other PHP code using FauxRequest
178 public function isInternalMode() {
179 return $this->mInternalMode;
183 * Return the request object that contains client's request
185 public function getRequest() {
186 return $this->mRequest;
190 * Get the ApiResult object associated with current request
192 public function getResult() {
193 return $this->mResult;
197 * Get the API module object. Only works after executeAction()
199 public function getModule() {
200 return $this->mModule;
204 * Only kept for backwards compatibility
205 * @deprecated Use isWriteMode() instead
207 public function requestWriteMode() {
208 if ( !$this->mEnableWrite ) {
209 $this->dieUsageMsg( array( 'writedisabled' ) );
211 if ( wfReadOnly() ) {
212 $this->dieUsageMsg( array( 'readonlytext' ) );
217 * Set how long the response should be cached.
219 public function setCacheMaxAge( $maxage ) {
220 $this->setCacheControl( array(
221 'max-age' => $maxage,
222 's-maxage' => $maxage
223 ) );
227 * Set directives (key/value pairs) for the Cache-Control header.
228 * Boolean values will be formatted as such, by including or omitting
229 * without an equals sign.
231 public function setCacheControl( $directives ) {
232 $this->mCacheControl = $directives + $this->mCacheControl;
236 * Create an instance of an output formatter by its name
238 public function createPrinterByName( $format ) {
239 if ( !isset( $this->mFormats[$format] ) ) {
240 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
242 return new $this->mFormats[$format] ( $this, $format );
246 * Execute api request. Any errors will be handled if the API was called by the remote client.
248 public function execute() {
249 $this->profileIn();
250 if ( $this->mInternalMode ) {
251 $this->executeAction();
252 } else {
253 $this->executeActionWithErrorHandling();
256 $this->profileOut();
260 * Execute an action, and in case of an error, erase whatever partial results
261 * have been accumulated, and replace it with an error message and a help screen.
263 protected function executeActionWithErrorHandling() {
264 // In case an error occurs during data output,
265 // clear the output buffer and print just the error information
266 ob_start();
268 try {
269 $this->executeAction();
270 } catch ( Exception $e ) {
271 // Log it
272 if ( $e instanceof MWException ) {
273 wfDebugLog( 'exception', $e->getLogMessage() );
277 // Handle any kind of exception by outputing properly formatted error message.
278 // If this fails, an unhandled exception should be thrown so that global error
279 // handler will process and log it.
282 $errCode = $this->substituteResultWithError( $e );
284 // Error results should not be cached
285 $this->setCacheMaxAge( 0 );
287 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
288 if ( $e->getCode() === 0 ) {
289 header( $headerStr );
290 } else {
291 header( $headerStr, true, $e->getCode() );
294 // Reset and print just the error message
295 ob_clean();
297 // If the error occured during printing, do a printer->profileOut()
298 $this->mPrinter->safeProfileOut();
299 $this->printResult( true );
302 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
303 if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
304 $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
306 if ( !isset( $this->mCacheControl['max-age'] ) ) {
307 $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
310 // Set the cache expiration at the last moment, as any errors may change the expiration.
311 // if $this->mSquidMaxage == 0, the expiry time is set to the first second of unix epoch
312 $exp = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
313 $expires = ( $exp == 0 ? 1 : time() + $exp );
314 header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expires ) );
316 // Construct the Cache-Control header
317 $ccHeader = '';
318 $separator = '';
319 foreach ( $this->mCacheControl as $name => $value ) {
320 if ( is_bool( $value ) ) {
321 if ( $value ) {
322 $ccHeader .= $separator . $name;
323 $separator = ', ';
325 } else {
326 $ccHeader .= $separator . "$name=$value";
327 $separator = ', ';
331 header( "Cache-Control: $ccHeader" );
333 if ( $this->mPrinter->getIsHtml() ) {
334 echo wfReportTime();
337 ob_end_flush();
341 * Replace the result data with the information about an exception.
342 * Returns the error code
344 protected function substituteResultWithError( $e ) {
345 // Printer may not be initialized if the extractRequestParams() fails for the main module
346 if ( !isset ( $this->mPrinter ) ) {
347 // The printer has not been created yet. Try to manually get formatter value.
348 $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
349 if ( !in_array( $value, $this->mFormatNames ) ) {
350 $value = self::API_DEFAULT_FORMAT;
353 $this->mPrinter = $this->createPrinterByName( $value );
354 if ( $this->mPrinter->getNeedsRawData() ) {
355 $this->getResult()->setRawMode();
359 if ( $e instanceof UsageException ) {
361 // User entered incorrect parameters - print usage screen
363 $errMessage = $e->getMessageArray();
365 // Only print the help message when this is for the developer, not runtime
366 if ( $this->mPrinter->getWantsHelp() || $this->mAction == 'help' ) {
367 ApiResult::setContent( $errMessage, $this->makeHelpMsg() );
370 } else {
371 global $wgShowSQLErrors, $wgShowExceptionDetails;
373 // Something is seriously wrong
375 if ( ( $e instanceof DBQueryError ) && !$wgShowSQLErrors ) {
376 $info = 'Database query error';
377 } else {
378 $info = "Exception Caught: {$e->getMessage()}";
381 $errMessage = array(
382 'code' => 'internal_api_error_' . get_class( $e ),
383 'info' => $info,
385 ApiResult::setContent( $errMessage, $wgShowExceptionDetails ? "\n\n{$e->getTraceAsString()}\n\n" : '' );
388 $this->getResult()->reset();
389 $this->getResult()->disableSizeCheck();
390 // Re-add the id
391 $requestid = $this->getParameter( 'requestid' );
392 if ( !is_null( $requestid ) ) {
393 $this->getResult()->addValue( null, 'requestid', $requestid );
395 $this->getResult()->addValue( null, 'error', $errMessage );
397 return $errMessage['code'];
401 * Set up for the execution.
403 protected function setupExecuteAction() {
404 // First add the id to the top element
405 $requestid = $this->getParameter( 'requestid' );
406 if ( !is_null( $requestid ) ) {
407 $this->getResult()->addValue( null, 'requestid', $requestid );
410 $params = $this->extractRequestParams();
412 $this->mShowVersions = $params['version'];
413 $this->mAction = $params['action'];
415 if ( !is_string( $this->mAction ) ) {
416 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
419 return $params;
423 * Set up the module for response
424 * @return Object the module that will handle this action
426 protected function setupModule() {
427 // Instantiate the module requested by the user
428 $module = new $this->mModules[$this->mAction] ( $this, $this->mAction );
429 $this->mModule = $module;
431 $moduleParams = $module->extractRequestParams();
433 // Die if token required, but not provided (unless there is a gettoken parameter)
434 $salt = $module->getTokenSalt();
435 if ( $salt !== false && !isset( $moduleParams['gettoken'] ) ) {
436 if ( !isset( $moduleParams['token'] ) ) {
437 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
438 } else {
439 global $wgUser;
440 if ( !$wgUser->matchEditToken( $moduleParams['token'], $salt ) ) {
441 $this->dieUsageMsg( array( 'sessionfailure' ) );
445 return $module;
449 * Check the max lag if necessary
450 * @param $params Array an array containing the request parameters.
451 * @return boolean True on success, false should exit immediately
453 protected function checkMaxLag($module, $params) {
454 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
455 // Check for maxlag
456 global $wgShowHostnames;
457 $maxLag = $params['maxlag'];
458 list( $host, $lag ) = wfGetLB()->getMaxLag();
459 if ( $lag > $maxLag ) {
460 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
461 header( 'X-Database-Lag: ' . intval( $lag ) );
462 if ( $wgShowHostnames ) {
463 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
464 } else {
465 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
467 return false;
470 return true;
475 * Check for sufficient permissions to execute
476 * @param $module object An Api module
478 protected function checkExecutePermissions($module) {
479 global $wgUser, $wgGroupPermissions;
480 if ( $module->isReadMode() && !$wgGroupPermissions['*']['read'] && !$wgUser->isAllowed( 'read' ) )
482 $this->dieUsageMsg( array( 'readrequired' ) );
484 if ( $module->isWriteMode() ) {
485 if ( !$this->mEnableWrite ) {
486 $this->dieUsageMsg( array( 'writedisabled' ) );
488 if ( !$wgUser->isAllowed( 'writeapi' ) ) {
489 $this->dieUsageMsg( array( 'writerequired' ) );
491 if ( wfReadOnly() ) {
492 $this->dieReadOnly();
498 * Check POST for external response and setup result printer
499 * @param $module object An Api module
500 * @param $params Array an array with the request parameters
502 protected function setupExternalResponse($module, $params) {
503 // Ignore mustBePosted() for internal calls
504 if ( $module->mustBePosted() && !$this->mRequest->wasPosted() ) {
505 $this->dieUsageMsg( array( 'mustbeposted', $this->mAction ) );
508 // See if custom printer is used
509 $this->mPrinter = $module->getCustomPrinter();
510 if ( is_null( $this->mPrinter ) ) {
511 // Create an appropriate printer
512 $this->mPrinter = $this->createPrinterByName( $params['format'] );
515 if ( $this->mPrinter->getNeedsRawData() ) {
516 $this->getResult()->setRawMode();
521 * Execute the actual module, without any error handling
523 protected function executeAction() {
524 $params = $this->setupExecuteAction();
525 $module = $this->setupModule();
527 $this->checkExecutePermissions($module);
529 if(!$this->checkMaxLag($module, $params)) return;
531 if ( !$this->mInternalMode ) {
532 $this->setupExternalResponse($module, $params);
535 // Execute
536 $module->profileIn();
537 $module->execute();
538 wfRunHooks( 'APIAfterExecute', array( &$module ) );
539 $module->profileOut();
541 if ( !$this->mInternalMode ) {
542 // Print result data
543 $this->printResult( false );
548 * Print results using the current printer
550 protected function printResult( $isError ) {
551 $this->getResult()->cleanUpUTF8();
552 $printer = $this->mPrinter;
553 $printer->profileIn();
556 * If the help message is requested in the default (xmlfm) format,
557 * tell the printer not to escape ampersands so that our links do
558 * not break.
560 $printer->setUnescapeAmps( ( $this->mAction == 'help' || $isError )
561 && $printer->getFormat() == 'XML' && $printer->getIsHtml() );
563 $printer->initPrinter( $isError );
565 $printer->execute();
566 $printer->closePrinter();
567 $printer->profileOut();
570 public function isReadMode() {
571 return false;
575 * See ApiBase for description.
577 public function getAllowedParams() {
578 return array(
579 'format' => array(
580 ApiBase::PARAM_DFLT => ApiMain::API_DEFAULT_FORMAT,
581 ApiBase::PARAM_TYPE => $this->mFormatNames
583 'action' => array(
584 ApiBase::PARAM_DFLT => 'help',
585 ApiBase::PARAM_TYPE => $this->mModuleNames
587 'version' => false,
588 'maxlag' => array(
589 ApiBase::PARAM_TYPE => 'integer'
591 'smaxage' => array(
592 ApiBase::PARAM_TYPE => 'integer',
593 ApiBase::PARAM_DFLT => 0
595 'maxage' => array(
596 ApiBase::PARAM_TYPE => 'integer',
597 ApiBase::PARAM_DFLT => 0
599 'requestid' => null,
604 * See ApiBase for description.
606 public function getParamDescription() {
607 return array(
608 'format' => 'The format of the output',
609 'action' => 'What action you would like to perform',
610 'version' => 'When showing help, include version for each module',
611 'maxlag' => 'Maximum lag',
612 'smaxage' => 'Set the s-maxage header to this many seconds. Errors are never cached',
613 'maxage' => 'Set the max-age header to this many seconds. Errors are never cached',
614 'requestid' => 'Request ID to distinguish requests. This will just be output back to you',
619 * See ApiBase for description.
621 public function getDescription() {
622 return array(
625 '******************************************************************',
626 '** **',
627 '** This is an auto-generated MediaWiki API documentation page **',
628 '** **',
629 '** Documentation and Examples: **',
630 '** http://www.mediawiki.org/wiki/API **',
631 '** **',
632 '******************************************************************',
634 'Status: All features shown on this page should be working, but the API',
635 ' is still in active development, and may change at any time.',
636 ' Make sure to monitor our mailing list for any updates.',
638 'Documentation: http://www.mediawiki.org/wiki/API',
639 'Mailing list: http://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
640 'Bugs & Requests: http://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
649 public function getPossibleErrors() {
650 return array_merge( parent::getPossibleErrors(), array(
651 array( 'readonlytext' ),
652 array( 'code' => 'unknown_format', 'info' => 'Unrecognized format: format' ),
653 array( 'code' => 'unknown_action', 'info' => 'The API requires a valid action parameter' ),
654 array( 'code' => 'maxlag', 'info' => 'Waiting for host: x seconds lagged' ),
655 array( 'code' => 'maxlag', 'info' => 'Waiting for a database server: x seconds lagged' ),
656 ) );
660 * Returns an array of strings with credits for the API
662 protected function getCredits() {
663 return array(
664 'API developers:',
665 ' Roan Kattouw <Firstname>.<Lastname>@home.nl (lead developer Sep 2007-present)',
666 ' Victor Vasiliev - vasilvv at gee mail dot com',
667 ' Bryan Tong Minh - bryan . tongminh @ gmail . com',
668 ' Sam Reed - sam @ reedyboy . net',
669 ' Yuri Astrakhan <Firstname><Lastname>@gmail.com (creator, lead developer Sep 2006-Sep 2007)',
671 'Please send your comments, suggestions and questions to mediawiki-api@lists.wikimedia.org',
672 'or file a bug report at http://bugzilla.wikimedia.org/'
677 * Override the parent to generate help messages for all available modules.
679 public function makeHelpMsg() {
680 global $wgMemc, $wgAPICacheHelp, $wgAPICacheHelpTimeout;
681 $this->mPrinter->setHelp();
682 // Get help text from cache if present
683 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
684 SpecialVersion::getVersion( 'nodb' ) .
685 $this->getMain()->getShowVersions() );
686 if ( $wgAPICacheHelp ) {
687 $cached = $wgMemc->get( $key );
688 if ( $cached ) {
689 return $cached;
692 $retval = $this->reallyMakeHelpMsg();
693 if ( $wgAPICacheHelp ) {
694 $wgMemc->set( $key, $retval, $wgAPICacheHelpTimeout );
696 return $retval;
699 public function reallyMakeHelpMsg() {
700 $this->mPrinter->setHelp();
702 // Use parent to make default message for the main module
703 $msg = parent::makeHelpMsg();
705 $astriks = str_repeat( '*** ', 10 );
706 $msg .= "\n\n$astriks Modules $astriks\n\n";
707 foreach ( $this->mModules as $moduleName => $unused ) {
708 $module = new $this->mModules[$moduleName] ( $this, $moduleName );
709 $msg .= self::makeHelpMsgHeader( $module, 'action' );
710 $msg2 = $module->makeHelpMsg();
711 if ( $msg2 !== false ) {
712 $msg .= $msg2;
714 $msg .= "\n";
717 $msg .= "\n$astriks Permissions $astriks\n\n";
718 foreach ( self::$mRights as $right => $rightMsg ) {
719 $groups = User::getGroupsWithPermission( $right );
720 $msg .= "* " . $right . " *\n " . wfMsgReplaceArgs( $rightMsg[ 'msg' ], $rightMsg[ 'params' ] ) .
721 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n";
725 $msg .= "\n$astriks Formats $astriks\n\n";
726 foreach ( $this->mFormats as $formatName => $unused ) {
727 $module = $this->createPrinterByName( $formatName );
728 $msg .= self::makeHelpMsgHeader( $module, 'format' );
729 $msg2 = $module->makeHelpMsg();
730 if ( $msg2 !== false ) {
731 $msg .= $msg2;
733 $msg .= "\n";
736 $msg .= "\n*** Credits: ***\n " . implode( "\n ", $this->getCredits() ) . "\n";
739 return $msg;
742 public static function makeHelpMsgHeader( $module, $paramName ) {
743 $modulePrefix = $module->getModulePrefix();
744 if ( strval( $modulePrefix ) !== '' ) {
745 $modulePrefix = "($modulePrefix) ";
748 return "* $paramName={$module->getModuleName()} $modulePrefix*";
751 private $mIsBot = null;
752 private $mIsSysop = null;
753 private $mCanApiHighLimits = null;
756 * Returns true if the currently logged in user is a bot, false otherwise
757 * OBSOLETE, use canApiHighLimits() instead
759 public function isBot() {
760 if ( !isset( $this->mIsBot ) ) {
761 global $wgUser;
762 $this->mIsBot = $wgUser->isAllowed( 'bot' );
764 return $this->mIsBot;
768 * Similar to isBot(), this method returns true if the logged in user is
769 * a sysop, and false if not.
770 * OBSOLETE, use canApiHighLimits() instead
772 public function isSysop() {
773 if ( !isset( $this->mIsSysop ) ) {
774 global $wgUser;
775 $this->mIsSysop = in_array( 'sysop', $wgUser->getGroups() );
778 return $this->mIsSysop;
782 * Check whether the current user is allowed to use high limits
783 * @return bool
785 public function canApiHighLimits() {
786 if ( !isset( $this->mCanApiHighLimits ) ) {
787 global $wgUser;
788 $this->mCanApiHighLimits = $wgUser->isAllowed( 'apihighlimits' );
791 return $this->mCanApiHighLimits;
795 * Check whether the user wants us to show version information in the API help
796 * @return bool
798 public function getShowVersions() {
799 return $this->mShowVersions;
803 * Returns the version information of this file, plus it includes
804 * the versions for all files that are not callable proper API modules
806 public function getVersion() {
807 $vers = array ();
808 $vers[] = 'MediaWiki: ' . SpecialVersion::getVersion() . "\n http://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/";
809 $vers[] = __CLASS__ . ': $Id$';
810 $vers[] = ApiBase::getBaseVersion();
811 $vers[] = ApiFormatBase::getBaseVersion();
812 $vers[] = ApiQueryBase::getBaseVersion();
813 return $vers;
817 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
818 * classes who wish to add their own modules to their lexicon or override the
819 * behavior of inherent ones.
821 * @param $mdlName String The identifier for this module.
822 * @param $mdlClass String The class where this module is implemented.
824 protected function addModule( $mdlName, $mdlClass ) {
825 $this->mModules[$mdlName] = $mdlClass;
829 * Add or overwrite an output format for this ApiMain. Intended for use by extending
830 * classes who wish to add to or modify current formatters.
832 * @param $fmtName The identifier for this format.
833 * @param $fmtClass The class implementing this format.
835 protected function addFormat( $fmtName, $fmtClass ) {
836 $this->mFormats[$fmtName] = $fmtClass;
840 * Get the array mapping module names to class names
842 function getModules() {
843 return $this->mModules;
848 * This exception will be thrown when dieUsage is called to stop module execution.
849 * The exception handling code will print a help screen explaining how this API may be used.
851 * @ingroup API
853 class UsageException extends Exception {
855 private $mCodestr;
856 private $mExtraData;
858 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
859 parent::__construct( $message, $code );
860 $this->mCodestr = $codestr;
861 $this->mExtraData = $extradata;
864 public function getCodeString() {
865 return $this->mCodestr;
868 public function getMessageArray() {
869 $result = array(
870 'code' => $this->mCodestr,
871 'info' => $this->getMessage()
873 if ( is_array( $this->mExtraData ) ) {
874 $result = array_merge( $result, $this->mExtraData );
876 return $result;
879 public function __toString() {
880 return "{$this->getCodeString()}: {$this->getMessage()}";