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