]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/api/ApiMain.php
MediaWiki 1.15.3
[autoinstalls/mediawiki.git] / includes / api / ApiMain.php
1 <?php
2
3 /*
4  * Created on Sep 4, 2006
5  *
6  * API for MediaWiki 1.8+
7  *
8  * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
9  *
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.
14  *
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.
19  *
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
24  */
25
26 if (!defined('MEDIAWIKI')) {
27         // Eclipse helper - will be ignored in production
28         require_once ('ApiBase.php');
29 }
30
31 /**
32  * @defgroup API API
33  */
34
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.
41  *
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.
45  *
46  * @ingroup API
47  */
48 class ApiMain extends ApiBase {
49
50         /**
51          * When no format parameter is given, this format will be used
52          */
53         const API_DEFAULT_FORMAT = 'xmlfm';
54
55         /**
56          * List of available modules: action name => module class
57          */
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                 'help' => 'ApiHelp',
67                 'paraminfo' => 'ApiParamInfo',
68
69                 // Write modules
70                 'purge' => 'ApiPurge',
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                 'emailuser' => 'ApiEmailUser',
80                 'watch' => 'ApiWatch',
81                 'patrol' => 'ApiPatrol',
82                 'import' => 'ApiImport',
83         );
84
85         /**
86          * List of available formats: format name => format class
87          */
88         private static $Formats = array (
89                 'json' => 'ApiFormatJson',
90                 'jsonfm' => 'ApiFormatJson',
91                 'php' => 'ApiFormatPhp',
92                 'phpfm' => 'ApiFormatPhp',
93                 'wddx' => 'ApiFormatWddx',
94                 'wddxfm' => 'ApiFormatWddx',
95                 'xml' => 'ApiFormatXml',
96                 'xmlfm' => 'ApiFormatXml',
97                 'yaml' => 'ApiFormatYaml',
98                 'yamlfm' => 'ApiFormatYaml',
99                 'rawfm' => 'ApiFormatJson',
100                 'txt' => 'ApiFormatTxt',
101                 'txtfm' => 'ApiFormatTxt',
102                 'dbg' => 'ApiFormatDbg',
103                 'dbgfm' => 'ApiFormatDbg'
104         );
105         
106         /**
107          * List of user roles that are specifically relevant to the API.
108          * array( 'right' => array ( 'msg'    => 'Some message with a $1',
109          *                           'params' => array ( $someVarToSubst ) ),
110          *                          );
111          */
112         private static $mRights = array('writeapi' => array(
113                                                 'msg' => 'Use of the write API',
114                                                 'params' => array()
115                                         ),
116                                         'apihighlimits' => array(
117                                                 '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.',
118                                                 'params' => array (ApiMain::LIMIT_SML2, ApiMain::LIMIT_BIG2)
119                                         )
120         );
121
122
123         private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
124         private $mResult, $mAction, $mShowVersions, $mEnableWrite, $mRequest, $mInternalMode, $mSquidMaxage;
125
126         /**
127         * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
128         *
129         * @param $request object - if this is an instance of FauxRequest, errors are thrown and no printing occurs
130         * @param $enableWrite bool should be set to true if the api may modify data
131         */
132         public function __construct($request, $enableWrite = false) {
133
134                 $this->mInternalMode = ($request instanceof FauxRequest);
135
136                 // Special handling for the main module: $parent === $this
137                 parent :: __construct($this, $this->mInternalMode ? 'main_int' : 'main');
138
139                 if (!$this->mInternalMode) {
140
141                         // Impose module restrictions.
142                         // If the current user cannot read,
143                         // Remove all modules other than login
144                         global $wgUser;
145
146                         if( $request->getVal( 'callback' ) !== null ) {
147                                 // JSON callback allows cross-site reads.
148                                 // For safety, strip user credentials.
149                                 wfDebug( "API: stripping user credentials for JSON callback\n" );
150                                 $wgUser = new User();
151                         }
152                 }
153
154                 global $wgAPIModules; // extension modules
155                 $this->mModules = $wgAPIModules + self :: $Modules;
156
157                 $this->mModuleNames = array_keys($this->mModules);
158                 $this->mFormats = self :: $Formats;
159                 $this->mFormatNames = array_keys($this->mFormats);
160
161                 $this->mResult = new ApiResult($this);
162                 $this->mShowVersions = false;
163                 $this->mEnableWrite = $enableWrite;
164
165                 $this->mRequest = & $request;
166
167                 $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling()
168                 $this->mCommit = false;
169         }
170
171         /**
172          * Return true if the API was started by other PHP code using FauxRequest
173          */
174         public function isInternalMode() {
175                 return $this->mInternalMode;
176         }
177
178         /**
179          * Return the request object that contains client's request
180          */
181         public function getRequest() {
182                 return $this->mRequest;
183         }
184
185         /**
186          * Get the ApiResult object asscosiated with current request
187          */
188         public function getResult() {
189                 return $this->mResult;
190         }
191
192         /**
193          * Only kept for backwards compatibility
194          * @deprecated Use isWriteMode() instead
195          */
196         public function requestWriteMode() {}
197
198         /**
199          * Set how long the response should be cached.
200          */
201         public function setCacheMaxAge($maxage) {
202                 $this->mSquidMaxage = $maxage;
203         }
204
205         /**
206          * Create an instance of an output formatter by its name
207          */
208         public function createPrinterByName($format) {
209                 if( !isset( $this->mFormats[$format] ) )
210                         $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
211                 return new $this->mFormats[$format] ($this, $format);
212         }
213
214         /**
215          * Execute api request. Any errors will be handled if the API was called by the remote client.
216          */
217         public function execute() {
218                 $this->profileIn();
219                 if ($this->mInternalMode)
220                         $this->executeAction();
221                 else
222                         $this->executeActionWithErrorHandling();
223         
224                 $this->profileOut();
225         }
226
227         /**
228          * Execute an action, and in case of an error, erase whatever partial results
229          * have been accumulated, and replace it with an error message and a help screen.
230          */
231         protected function executeActionWithErrorHandling() {
232
233                 // In case an error occurs during data output,
234                 // clear the output buffer and print just the error information
235                 ob_start();
236
237                 try {
238                         $this->executeAction();
239                 } catch (Exception $e) {
240                         // Log it
241                         if ( $e instanceof MWException ) {
242                                 wfDebugLog( 'exception', $e->getLogMessage() );
243                         }
244
245                         //
246                         // Handle any kind of exception by outputing properly formatted error message.
247                         // If this fails, an unhandled exception should be thrown so that global error
248                         // handler will process and log it.
249                         //
250
251                         $errCode = $this->substituteResultWithError($e);
252
253                         // Error results should not be cached
254                         $this->setCacheMaxAge(0);
255
256                         $headerStr = 'MediaWiki-API-Error: ' . $errCode;
257                         if ($e->getCode() === 0)
258                                 header($headerStr);
259                         else
260                                 header($headerStr, true, $e->getCode());
261
262                         // Reset and print just the error message
263                         ob_clean();
264
265                         // If the error occured during printing, do a printer->profileOut()
266                         $this->mPrinter->safeProfileOut();
267                         $this->printResult(true);
268                 }
269
270                 if($this->mSquidMaxage == -1)
271                 {
272                         # Nobody called setCacheMaxAge(), use the (s)maxage parameters
273                         $smaxage = $this->getParameter('smaxage');
274                         $maxage = $this->getParameter('maxage');
275                 }
276                 else
277                         $smaxage = $maxage = $this->mSquidMaxage;
278
279                 // Set the cache expiration at the last moment, as any errors may change the expiration.
280                 // if $this->mSquidMaxage == 0, the expiry time is set to the first second of unix epoch
281                 $exp = min($smaxage, $maxage);
282                 $expires = ($exp == 0 ? 1 : time() + $exp);
283                 header('Expires: ' . wfTimestamp(TS_RFC2822, $expires));
284                 header('Cache-Control: s-maxage=' . $smaxage . ', must-revalidate, max-age=' . $maxage);
285
286                 if($this->mPrinter->getIsHtml())
287                         echo wfReportTime();
288
289                 ob_end_flush();
290         }
291
292         /**
293          * Replace the result data with the information about an exception.
294          * Returns the error code
295          */
296         protected function substituteResultWithError($e) {
297
298                         // Printer may not be initialized if the extractRequestParams() fails for the main module
299                         if (!isset ($this->mPrinter)) {
300                                 // The printer has not been created yet. Try to manually get formatter value.
301                                 $value = $this->getRequest()->getVal('format', self::API_DEFAULT_FORMAT);
302                                 if (!in_array($value, $this->mFormatNames))
303                                         $value = self::API_DEFAULT_FORMAT;
304
305                                 $this->mPrinter = $this->createPrinterByName($value);
306                                 if ($this->mPrinter->getNeedsRawData())
307                                         $this->getResult()->setRawMode();
308                         }
309
310                         if ($e instanceof UsageException) {
311                                 //
312                                 // User entered incorrect parameters - print usage screen
313                                 //
314                                 $errMessage = array (
315                                 'code' => $e->getCodeString(),
316                                 'info' => $e->getMessage());
317
318                                 // Only print the help message when this is for the developer, not runtime
319                                 if ($this->mPrinter->getIsHtml() || $this->mAction == 'help')
320                                         ApiResult :: setContent($errMessage, $this->makeHelpMsg());
321
322                         } else {
323                                 global $wgShowSQLErrors, $wgShowExceptionDetails;
324                                 //
325                                 // Something is seriously wrong
326                                 //
327                                 if ( ( $e instanceof DBQueryError ) && !$wgShowSQLErrors ) {
328                                         $info = "Database query error";
329                                 } else {
330                                         $info = "Exception Caught: {$e->getMessage()}";
331                                 }
332
333                                 $errMessage = array (
334                                         'code' => 'internal_api_error_'. get_class($e),
335                                         'info' => $info,
336                                 );
337                                 ApiResult :: setContent($errMessage, $wgShowExceptionDetails ? "\n\n{$e->getTraceAsString()}\n\n" : "" );                               
338                         }
339
340                         $this->getResult()->reset();
341                         $this->getResult()->disableSizeCheck();
342                         // Re-add the id
343                         $requestid = $this->getParameter('requestid');
344                         if(!is_null($requestid))
345                                 $this->getResult()->addValue(null, 'requestid', $requestid);
346                         $this->getResult()->addValue(null, 'error', $errMessage);
347
348                 return $errMessage['code'];
349         }
350
351         /**
352          * Execute the actual module, without any error handling
353          */
354         protected function executeAction() {
355                 // First add the id to the top element
356                 $requestid = $this->getParameter('requestid');
357                 if(!is_null($requestid))
358                         $this->getResult()->addValue(null, 'requestid', $requestid);
359
360                 $params = $this->extractRequestParams();
361
362                 $this->mShowVersions = $params['version'];
363                 $this->mAction = $params['action'];
364
365                 if( !is_string( $this->mAction ) ) {
366                         $this->dieUsage( "The API requires a valid action parameter", 'unknown_action' );
367                 }
368
369                 // Instantiate the module requested by the user
370                 $module = new $this->mModules[$this->mAction] ($this, $this->mAction);
371
372                 if( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
373                         // Check for maxlag
374                         global $wgShowHostnames;
375                         $maxLag = $params['maxlag'];
376                         list( $host, $lag ) = wfGetLB()->getMaxLag();
377                         if ( $lag > $maxLag ) {
378                                 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
379                                 header( 'X-Database-Lag: ' . intval( $lag ) );
380                                 // XXX: should we return a 503 HTTP error code like wfMaxlagError() does?
381                                 if( $wgShowHostnames ) {
382                                         $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
383                                 } else {
384                                         $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
385                                 }
386                                 return;
387                         }
388                 }
389
390                 global $wgUser;
391                 if ($module->isReadMode() && !$wgUser->isAllowed('read'))
392                         $this->dieUsageMsg(array('readrequired'));
393                 if ($module->isWriteMode()) {
394                         if (!$this->mEnableWrite)
395                                 $this->dieUsageMsg(array('writedisabled'));
396                         if (!$wgUser->isAllowed('writeapi'))
397                                 $this->dieUsageMsg(array('writerequired'));
398                         if (wfReadOnly())
399                                 $this->dieUsageMsg(array('readonlytext'));
400                 }
401
402                 if (!$this->mInternalMode) {
403                         // Ignore mustBePosted() for internal calls
404                         if($module->mustBePosted() && !$this->mRequest->wasPosted())
405                                 $this->dieUsage("The {$this->mAction} module requires a POST request", 'mustbeposted');
406
407                         // See if custom printer is used
408                         $this->mPrinter = $module->getCustomPrinter();
409                         if (is_null($this->mPrinter)) {
410                                 // Create an appropriate printer
411                                 $this->mPrinter = $this->createPrinterByName($params['format']);
412                         }
413
414                         if ($this->mPrinter->getNeedsRawData())
415                                 $this->getResult()->setRawMode();
416                 }
417
418                 // Execute
419                 $module->profileIn();
420                 $module->execute();
421                 wfRunHooks('APIAfterExecute', array(&$module));
422                 $module->profileOut();
423
424                 if (!$this->mInternalMode) {
425                         // Print result data
426                         $this->printResult(false);
427                 }
428         }
429
430         /**
431          * Print results using the current printer
432          */
433         protected function printResult($isError) {
434                 $this->getResult()->cleanUpUTF8();
435                 $printer = $this->mPrinter;
436                 $printer->profileIn();
437
438                 /* If the help message is requested in the default (xmlfm) format,
439                  * tell the printer not to escape ampersands so that our links do
440                  * not break. */
441                 $printer->setUnescapeAmps ( ( $this->mAction == 'help' || $isError )
442                                 && $printer->getFormat() == 'XML' && $printer->getIsHtml() );
443
444                 $printer->initPrinter($isError);
445
446                 $printer->execute();
447                 $printer->closePrinter();
448                 $printer->profileOut();
449         }
450         
451         public function isReadMode() {
452                 return false;
453         }
454
455         /**
456          * See ApiBase for description.
457          */
458         public function getAllowedParams() {
459                 return array (
460                         'format' => array (
461                                 ApiBase :: PARAM_DFLT => ApiMain :: API_DEFAULT_FORMAT,
462                                 ApiBase :: PARAM_TYPE => $this->mFormatNames
463                         ),
464                         'action' => array (
465                                 ApiBase :: PARAM_DFLT => 'help',
466                                 ApiBase :: PARAM_TYPE => $this->mModuleNames
467                         ),
468                         'version' => false,
469                         'maxlag'  => array (
470                                 ApiBase :: PARAM_TYPE => 'integer'
471                         ),
472                         'smaxage' => array (
473                                 ApiBase :: PARAM_TYPE => 'integer',
474                                 ApiBase :: PARAM_DFLT => 0
475                         ),
476                         'maxage' => array (
477                                 ApiBase :: PARAM_TYPE => 'integer',
478                                 ApiBase :: PARAM_DFLT => 0
479                         ),
480                         'requestid' => null,
481                 );
482         }
483
484         /**
485          * See ApiBase for description.
486          */
487         public function getParamDescription() {
488                 return array (
489                         'format' => 'The format of the output',
490                         'action' => 'What action you would like to perform',
491                         'version' => 'When showing help, include version for each module',
492                         'maxlag' => 'Maximum lag',
493                         'smaxage' => 'Set the s-maxage header to this many seconds. Errors are never cached',
494                         'maxage' => 'Set the max-age header to this many seconds. Errors are never cached',
495                         'requestid' => 'Request ID to distinguish requests. This will just be output back to you',
496                 );
497         }
498
499         /**
500          * See ApiBase for description.
501          */
502         public function getDescription() {
503                 return array (
504                         '',
505                         '',
506                         '******************************************************************',
507                         '**                                                              **',
508                         '**  This is an auto-generated MediaWiki API documentation page  **',
509                         '**                                                              **',
510                         '**                  Documentation and Examples:                 **',
511                         '**               http://www.mediawiki.org/wiki/API              **',
512                         '**                                                              **',
513                         '******************************************************************',
514                         '',
515                         'Status:          All features shown on this page should be working, but the API',
516                         '                 is still in active development, and  may change at any time.',
517                         '                 Make sure to monitor our mailing list for any updates.',
518                         '',
519                         'Documentation:   http://www.mediawiki.org/wiki/API',
520                         'Mailing list:    http://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
521                         'Bugs & Requests: http://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
522                         '',
523                         '',
524                         '',
525                         '',
526                         '',
527                 );
528         }
529
530         /**
531          * Returns an array of strings with credits for the API
532          */
533         protected function getCredits() {
534                 return array(
535                         'API developers:',
536                         '    Roan Kattouw <Firstname>.<Lastname>@home.nl (lead developer Sep 2007-present)',
537                         '    Victor Vasiliev - vasilvv at gee mail dot com',
538                         '    Bryan Tong Minh - bryan . tongminh @ gmail . com',
539                         '    Yuri Astrakhan <Firstname><Lastname>@gmail.com (creator, lead developer Sep 2006-Sep 2007)',
540                         '',
541                         'Please send your comments, suggestions and questions to mediawiki-api@lists.wikimedia.org',
542                         'or file a bug report at http://bugzilla.wikimedia.org/'
543                 );
544         }
545
546         /**
547          * Override the parent to generate help messages for all available modules.
548          */
549         public function makeHelpMsg() {
550
551                 $this->mPrinter->setHelp();
552
553                 // Use parent to make default message for the main module
554                 $msg = parent :: makeHelpMsg();
555
556                 $astriks = str_repeat('*** ', 10);
557                 $msg .= "\n\n$astriks Modules  $astriks\n\n";
558                 foreach( $this->mModules as $moduleName => $unused ) {
559                         $module = new $this->mModules[$moduleName] ($this, $moduleName);
560                         $msg .= self::makeHelpMsgHeader($module, 'action');
561                         $msg2 = $module->makeHelpMsg();
562                         if ($msg2 !== false)
563                                 $msg .= $msg2;
564                         $msg .= "\n";
565                 }
566
567                 $msg .= "\n$astriks Permissions $astriks\n\n";
568                 foreach ( self :: $mRights as $right => $rightMsg ) {
569                         $groups = User::getGroupsWithPermission( $right );
570                         $msg .= "* " . $right . " *\n  " . wfMsgReplaceArgs( $rightMsg[ 'msg' ], $rightMsg[ 'params' ] ) . 
571                                                 "\nGranted to:\n  " . str_replace( "*", "all", implode( ", ", $groups ) ) . "\n";
572
573                 }
574
575                 $msg .= "\n$astriks Formats  $astriks\n\n";
576                 foreach( $this->mFormats as $formatName => $unused ) {
577                         $module = $this->createPrinterByName($formatName);
578                         $msg .= self::makeHelpMsgHeader($module, 'format');
579                         $msg2 = $module->makeHelpMsg();
580                         if ($msg2 !== false)
581                                 $msg .= $msg2;
582                         $msg .= "\n";
583                 }
584
585                 $msg .= "\n*** Credits: ***\n   " . implode("\n   ", $this->getCredits()) . "\n";
586
587
588                 return $msg;
589         }
590
591         public static function makeHelpMsgHeader($module, $paramName) {
592                 $modulePrefix = $module->getModulePrefix();
593                 if (strval($modulePrefix) !== '')
594                         $modulePrefix = "($modulePrefix) ";
595
596                 return "* $paramName={$module->getModuleName()} $modulePrefix*";
597         }
598
599         private $mIsBot = null;
600         private $mIsSysop = null;
601         private $mCanApiHighLimits = null;
602
603         /**
604          * Returns true if the currently logged in user is a bot, false otherwise
605          * OBSOLETE, use canApiHighLimits() instead
606          */
607         public function isBot() {
608                 if (!isset ($this->mIsBot)) {
609                         global $wgUser;
610                         $this->mIsBot = $wgUser->isAllowed('bot');
611                 }
612                 return $this->mIsBot;
613         }
614
615         /**
616          * Similar to isBot(), this method returns true if the logged in user is
617          * a sysop, and false if not.
618          * OBSOLETE, use canApiHighLimits() instead
619          */
620         public function isSysop() {
621                 if (!isset ($this->mIsSysop)) {
622                         global $wgUser;
623                         $this->mIsSysop = in_array( 'sysop', $wgUser->getGroups());
624                 }
625
626                 return $this->mIsSysop;
627         }
628
629         /**
630          * Check whether the current user is allowed to use high limits
631          * @return bool
632          */
633         public function canApiHighLimits() {
634                 if (!isset($this->mCanApiHighLimits)) {
635                         global $wgUser;
636                         $this->mCanApiHighLimits = $wgUser->isAllowed('apihighlimits');
637                 }
638
639                 return $this->mCanApiHighLimits;
640         }
641
642         /**
643          * Check whether the user wants us to show version information in the API help
644          * @return bool
645          */
646         public function getShowVersions() {
647                 return $this->mShowVersions;
648         }
649
650         /**
651          * Returns the version information of this file, plus it includes
652          * the versions for all files that are not callable proper API modules
653          */
654         public function getVersion() {
655                 $vers = array ();
656                 $vers[] = 'MediaWiki: ' . SpecialVersion::getVersion() . "\n    http://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/";
657                 $vers[] = __CLASS__ . ': $Id: ApiMain.php 50834 2009-05-20 20:10:47Z catrope $';
658                 $vers[] = ApiBase :: getBaseVersion();
659                 $vers[] = ApiFormatBase :: getBaseVersion();
660                 $vers[] = ApiQueryBase :: getBaseVersion();
661                 $vers[] = ApiFormatFeedWrapper :: getVersion(); // not accessible with format=xxx
662                 return $vers;
663         }
664
665         /**
666          * Add or overwrite a module in this ApiMain instance. Intended for use by extending
667          * classes who wish to add their own modules to their lexicon or override the
668          * behavior of inherent ones.
669          *
670          * @access protected
671          * @param $mdlName String The identifier for this module.
672          * @param $mdlClass String The class where this module is implemented.
673          */
674         protected function addModule( $mdlName, $mdlClass ) {
675                 $this->mModules[$mdlName] = $mdlClass;
676         }
677
678         /**
679          * Add or overwrite an output format for this ApiMain. Intended for use by extending
680          * classes who wish to add to or modify current formatters.
681          *
682          * @access protected
683          * @param $fmtName The identifier for this format.
684          * @param $fmtClass The class implementing this format.
685          */
686         protected function addFormat( $fmtName, $fmtClass ) {
687                 $this->mFormats[$fmtName] = $fmtClass;
688         }
689
690         /**
691          * Get the array mapping module names to class names
692          */
693         function getModules() {
694                 return $this->mModules;
695         }
696 }
697
698 /**
699  * This exception will be thrown when dieUsage is called to stop module execution.
700  * The exception handling code will print a help screen explaining how this API may be used.
701  *
702  * @ingroup API
703  */
704 class UsageException extends Exception {
705
706         private $mCodestr;
707
708         public function __construct($message, $codestr, $code = 0) {
709                 parent :: __construct($message, $code);
710                 $this->mCodestr = $codestr;
711         }
712         public function getCodeString() {
713                 return $this->mCodestr;
714         }
715         public function __toString() {
716                 return "{$this->getCodeString()}: {$this->getMessage()}";
717         }
718 }