Fix param names mismatch in code/doc from r64852 and r64397
[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 © 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 'go' => 'ApiGo',
67 'help' => 'ApiHelp',
68 'paraminfo' => 'ApiParamInfo',
69
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',
86 );
87
88 /**
89 * List of available formats: format name => format class
90 */
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'
107 );
108
109 /**
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 * );
114 */
115 private static $mRights = array(
116 'writeapi' => array(
117 'msg' => 'Use of the write API',
118 'params' => array()
119 ),
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 )
123 )
124 );
125
126 private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
127 private $mResult, $mAction, $mShowVersions, $mEnableWrite, $mRequest;
128 private $mInternalMode, $mSquidMaxage, $mModule;
129
130 private $mCacheControl = array( 'must-revalidate' => true );
131
132 /**
133 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
134 *
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
137 */
138 public function __construct( $request, $enableWrite = false ) {
139 $this->mInternalMode = ( $request instanceof FauxRequest );
140
141 // Special handling for the main module: $parent === $this
142 parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' );
143
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;
149
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();
155 }
156 }
157
158 global $wgAPIModules; // extension modules
159 $this->mModules = $wgAPIModules + self::$Modules;
160
161 $this->mModuleNames = array_keys( $this->mModules );
162 $this->mFormats = self::$Formats;
163 $this->mFormatNames = array_keys( $this->mFormats );
164
165 $this->mResult = new ApiResult( $this );
166 $this->mShowVersions = false;
167 $this->mEnableWrite = $enableWrite;
168
169 $this->mRequest = &$request;
170
171 $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling()
172 $this->mCommit = false;
173 }
174
175 /**
176 * Return true if the API was started by other PHP code using FauxRequest
177 */
178 public function isInternalMode() {
179 return $this->mInternalMode;
180 }
181
182 /**
183 * Return the request object that contains client's request
184 */
185 public function getRequest() {
186 return $this->mRequest;
187 }
188
189 /**
190 * Get the ApiResult object associated with current request
191 */
192 public function getResult() {
193 return $this->mResult;
194 }
195
196 /**
197 * Get the API module object. Only works after executeAction()
198 */
199 public function getModule() {
200 return $this->mModule;
201 }
202
203 /**
204 * Only kept for backwards compatibility
205 * @deprecated Use isWriteMode() instead
206 */
207 public function requestWriteMode() {
208 if ( !$this->mEnableWrite ) {
209 $this->dieUsageMsg( array( 'writedisabled' ) );
210 }
211 if ( wfReadOnly() ) {
212 $this->dieUsageMsg( array( 'readonlytext' ) );
213 }
214 }
215
216 /**
217 * Set how long the response should be cached.
218 */
219 public function setCacheMaxAge( $maxage ) {
220 $this->setCacheControl( array(
221 'max-age' => $maxage,
222 's-maxage' => $maxage
223 ) );
224 }
225
226 /**
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.
230 */
231 public function setCacheControl( $directives ) {
232 $this->mCacheControl = $directives + $this->mCacheControl;
233 }
234
235 /**
236 * Create an instance of an output formatter by its name
237 */
238 public function createPrinterByName( $format ) {
239 if ( !isset( $this->mFormats[$format] ) ) {
240 $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' );
241 }
242 return new $this->mFormats[$format] ( $this, $format );
243 }
244
245 /**
246 * Execute api request. Any errors will be handled if the API was called by the remote client.
247 */
248 public function execute() {
249 $this->profileIn();
250 if ( $this->mInternalMode ) {
251 $this->executeAction();
252 } else {
253 $this->executeActionWithErrorHandling();
254 }
255
256 $this->profileOut();
257 }
258
259 /**
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.
262 */
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();
267
268 try {
269 $this->executeAction();
270 } catch ( Exception $e ) {
271 // Log it
272 if ( $e instanceof MWException ) {
273 wfDebugLog( 'exception', $e->getLogMessage() );
274 }
275
276 //
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.
280 //
281
282 $errCode = $this->substituteResultWithError( $e );
283
284 // Error results should not be cached
285 $this->setCacheMaxAge( 0 );
286
287 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
288 if ( $e->getCode() === 0 ) {
289 header( $headerStr );
290 } else {
291 header( $headerStr, true, $e->getCode() );
292 }
293
294 // Reset and print just the error message
295 ob_clean();
296
297 // If the error occured during printing, do a printer->profileOut()
298 $this->mPrinter->safeProfileOut();
299 $this->printResult( true );
300 }
301
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' );
305 }
306 if ( !isset( $this->mCacheControl['max-age'] ) ) {
307 $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
308 }
309
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 ) );
315
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 = ', ';
324 }
325 } else {
326 $ccHeader .= $separator . "$name=$value";
327 $separator = ', ';
328 }
329 }
330
331 header( "Cache-Control: $ccHeader" );
332
333 if ( $this->mPrinter->getIsHtml() ) {
334 echo wfReportTime();
335 }
336
337 ob_end_flush();
338 }
339
340 /**
341 * Replace the result data with the information about an exception.
342 * Returns the error code
343 */
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;
351 }
352
353 $this->mPrinter = $this->createPrinterByName( $value );
354 if ( $this->mPrinter->getNeedsRawData() ) {
355 $this->getResult()->setRawMode();
356 }
357 }
358
359 if ( $e instanceof UsageException ) {
360 //
361 // User entered incorrect parameters - print usage screen
362 //
363 $errMessage = $e->getMessageArray();
364
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() );
368 }
369
370 } else {
371 global $wgShowSQLErrors, $wgShowExceptionDetails;
372 //
373 // Something is seriously wrong
374 //
375 if ( ( $e instanceof DBQueryError ) && !$wgShowSQLErrors ) {
376 $info = 'Database query error';
377 } else {
378 $info = "Exception Caught: {$e->getMessage()}";
379 }
380
381 $errMessage = array(
382 'code' => 'internal_api_error_' . get_class( $e ),
383 'info' => $info,
384 );
385 ApiResult::setContent( $errMessage, $wgShowExceptionDetails ? "\n\n{$e->getTraceAsString()}\n\n" : '' );
386 }
387
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 );
394 }
395 $this->getResult()->addValue( null, 'error', $errMessage );
396
397 return $errMessage['code'];
398 }
399
400 /**
401 * Set up for the execution.
402 */
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 );
408 }
409
410 $params = $this->extractRequestParams();
411
412 $this->mShowVersions = $params['version'];
413 $this->mAction = $params['action'];
414
415 if ( !is_string( $this->mAction ) ) {
416 $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' );
417 }
418
419 return $params;
420 }
421
422 /**
423 * Set up the module for response
424 * @return Object the module that will handle this action
425 */
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;
430
431 $moduleParams = $module->extractRequestParams();
432
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' ) );
442 }
443 }
444 }
445 return $module;
446 }
447
448 /**
449 * Check the max lag if necessary
450 * @param $module ApiBase object: Api module being used
451 * @param $params Array an array containing the request parameters.
452 * @return boolean True on success, false should exit immediately
453 */
454 protected function checkMaxLag($module, $params) {
455 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
456 // Check for maxlag
457 global $wgShowHostnames;
458 $maxLag = $params['maxlag'];
459 list( $host, $lag ) = wfGetLB()->getMaxLag();
460 if ( $lag > $maxLag ) {
461 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
462 header( 'X-Database-Lag: ' . intval( $lag ) );
463 if ( $wgShowHostnames ) {
464 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
465 } else {
466 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
467 }
468 return false;
469 }
470 }
471 return true;
472 }
473
474
475 /**
476 * Check for sufficient permissions to execute
477 * @param $module object An Api module
478 */
479 protected function checkExecutePermissions($module) {
480 global $wgUser, $wgGroupPermissions;
481 if ( $module->isReadMode() && !$wgGroupPermissions['*']['read'] && !$wgUser->isAllowed( 'read' ) )
482 {
483 $this->dieUsageMsg( array( 'readrequired' ) );
484 }
485 if ( $module->isWriteMode() ) {
486 if ( !$this->mEnableWrite ) {
487 $this->dieUsageMsg( array( 'writedisabled' ) );
488 }
489 if ( !$wgUser->isAllowed( 'writeapi' ) ) {
490 $this->dieUsageMsg( array( 'writerequired' ) );
491 }
492 if ( wfReadOnly() ) {
493 $this->dieReadOnly();
494 }
495 }
496 }
497
498 /**
499 * Check POST for external response and setup result printer
500 * @param $module object An Api module
501 * @param $params Array an array with the request parameters
502 */
503 protected function setupExternalResponse($module, $params) {
504 // Ignore mustBePosted() for internal calls
505 if ( $module->mustBePosted() && !$this->mRequest->wasPosted() ) {
506 $this->dieUsageMsg( array( 'mustbeposted', $this->mAction ) );
507 }
508
509 // See if custom printer is used
510 $this->mPrinter = $module->getCustomPrinter();
511 if ( is_null( $this->mPrinter ) ) {
512 // Create an appropriate printer
513 $this->mPrinter = $this->createPrinterByName( $params['format'] );
514 }
515
516 if ( $this->mPrinter->getNeedsRawData() ) {
517 $this->getResult()->setRawMode();
518 }
519 }
520
521 /**
522 * Execute the actual module, without any error handling
523 */
524 protected function executeAction() {
525 $params = $this->setupExecuteAction();
526 $module = $this->setupModule();
527
528 $this->checkExecutePermissions($module);
529
530 if(!$this->checkMaxLag($module, $params)) return;
531
532 if ( !$this->mInternalMode ) {
533 $this->setupExternalResponse($module, $params);
534 }
535
536 // Execute
537 $module->profileIn();
538 $module->execute();
539 wfRunHooks( 'APIAfterExecute', array( &$module ) );
540 $module->profileOut();
541
542 if ( !$this->mInternalMode ) {
543 // Print result data
544 $this->printResult( false );
545 }
546 }
547
548 /**
549 * Print results using the current printer
550 */
551 protected function printResult( $isError ) {
552 $this->getResult()->cleanUpUTF8();
553 $printer = $this->mPrinter;
554 $printer->profileIn();
555
556 /**
557 * If the help message is requested in the default (xmlfm) format,
558 * tell the printer not to escape ampersands so that our links do
559 * not break.
560 */
561 $printer->setUnescapeAmps( ( $this->mAction == 'help' || $isError )
562 && $printer->getFormat() == 'XML' && $printer->getIsHtml() );
563
564 $printer->initPrinter( $isError );
565
566 $printer->execute();
567 $printer->closePrinter();
568 $printer->profileOut();
569 }
570
571 public function isReadMode() {
572 return false;
573 }
574
575 /**
576 * See ApiBase for description.
577 */
578 public function getAllowedParams() {
579 return array(
580 'format' => array(
581 ApiBase::PARAM_DFLT => ApiMain::API_DEFAULT_FORMAT,
582 ApiBase::PARAM_TYPE => $this->mFormatNames
583 ),
584 'action' => array(
585 ApiBase::PARAM_DFLT => 'help',
586 ApiBase::PARAM_TYPE => $this->mModuleNames
587 ),
588 'version' => false,
589 'maxlag' => array(
590 ApiBase::PARAM_TYPE => 'integer'
591 ),
592 'smaxage' => array(
593 ApiBase::PARAM_TYPE => 'integer',
594 ApiBase::PARAM_DFLT => 0
595 ),
596 'maxage' => array(
597 ApiBase::PARAM_TYPE => 'integer',
598 ApiBase::PARAM_DFLT => 0
599 ),
600 'requestid' => null,
601 );
602 }
603
604 /**
605 * See ApiBase for description.
606 */
607 public function getParamDescription() {
608 return array(
609 'format' => 'The format of the output',
610 'action' => 'What action you would like to perform',
611 'version' => 'When showing help, include version for each module',
612 'maxlag' => 'Maximum lag',
613 'smaxage' => 'Set the s-maxage header to this many seconds. Errors are never cached',
614 'maxage' => 'Set the max-age header to this many seconds. Errors are never cached',
615 'requestid' => 'Request ID to distinguish requests. This will just be output back to you',
616 );
617 }
618
619 /**
620 * See ApiBase for description.
621 */
622 public function getDescription() {
623 return array(
624 '',
625 '',
626 '******************************************************************',
627 '** **',
628 '** This is an auto-generated MediaWiki API documentation page **',
629 '** **',
630 '** Documentation and Examples: **',
631 '** http://www.mediawiki.org/wiki/API **',
632 '** **',
633 '******************************************************************',
634 '',
635 'Status: All features shown on this page should be working, but the API',
636 ' is still in active development, and may change at any time.',
637 ' Make sure to monitor our mailing list for any updates.',
638 '',
639 'Documentation: http://www.mediawiki.org/wiki/API',
640 'Mailing list: http://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
641 'Api Announcements: http://lists.wikimedia.org/mailman/listinfo/mediawiki-api-announce',
642 'Bugs & Requests: http://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
643 '',
644 '',
645 '',
646 '',
647 '',
648 );
649 }
650
651 public function getPossibleErrors() {
652 return array_merge( parent::getPossibleErrors(), array(
653 array( 'readonlytext' ),
654 array( 'code' => 'unknown_format', 'info' => 'Unrecognized format: format' ),
655 array( 'code' => 'unknown_action', 'info' => 'The API requires a valid action parameter' ),
656 array( 'code' => 'maxlag', 'info' => 'Waiting for host: x seconds lagged' ),
657 array( 'code' => 'maxlag', 'info' => 'Waiting for a database server: x seconds lagged' ),
658 ) );
659 }
660
661 /**
662 * Returns an array of strings with credits for the API
663 */
664 protected function getCredits() {
665 return array(
666 'API developers:',
667 ' Roan Kattouw <Firstname>.<Lastname>@home.nl (lead developer Sep 2007-present)',
668 ' Victor Vasiliev - vasilvv at gee mail dot com',
669 ' Bryan Tong Minh - bryan . tongminh @ gmail . com',
670 ' Sam Reed - sam @ reedyboy . net',
671 ' Yuri Astrakhan <Firstname><Lastname>@gmail.com (creator, lead developer Sep 2006-Sep 2007)',
672 '',
673 'Please send your comments, suggestions and questions to mediawiki-api@lists.wikimedia.org',
674 'or file a bug report at http://bugzilla.wikimedia.org/'
675 );
676 }
677
678 /**
679 * Override the parent to generate help messages for all available modules.
680 */
681 public function makeHelpMsg() {
682 global $wgMemc, $wgAPICacheHelp, $wgAPICacheHelpTimeout;
683 $this->mPrinter->setHelp();
684 // Get help text from cache if present
685 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
686 SpecialVersion::getVersion( 'nodb' ) .
687 $this->getMain()->getShowVersions() );
688 if ( $wgAPICacheHelp ) {
689 $cached = $wgMemc->get( $key );
690 if ( $cached ) {
691 return $cached;
692 }
693 }
694 $retval = $this->reallyMakeHelpMsg();
695 if ( $wgAPICacheHelp ) {
696 $wgMemc->set( $key, $retval, $wgAPICacheHelpTimeout );
697 }
698 return $retval;
699 }
700
701 public function reallyMakeHelpMsg() {
702 $this->mPrinter->setHelp();
703
704 // Use parent to make default message for the main module
705 $msg = parent::makeHelpMsg();
706
707 $astriks = str_repeat( '*** ', 10 );
708 $msg .= "\n\n$astriks Modules $astriks\n\n";
709 foreach ( $this->mModules as $moduleName => $unused ) {
710 $module = new $this->mModules[$moduleName] ( $this, $moduleName );
711 $msg .= self::makeHelpMsgHeader( $module, 'action' );
712 $msg2 = $module->makeHelpMsg();
713 if ( $msg2 !== false ) {
714 $msg .= $msg2;
715 }
716 $msg .= "\n";
717 }
718
719 $msg .= "\n$astriks Permissions $astriks\n\n";
720 foreach ( self::$mRights as $right => $rightMsg ) {
721 $groups = User::getGroupsWithPermission( $right );
722 $msg .= "* " . $right . " *\n " . wfMsgReplaceArgs( $rightMsg[ 'msg' ], $rightMsg[ 'params' ] ) .
723 "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n";
724
725 }
726
727 $msg .= "\n$astriks Formats $astriks\n\n";
728 foreach ( $this->mFormats as $formatName => $unused ) {
729 $module = $this->createPrinterByName( $formatName );
730 $msg .= self::makeHelpMsgHeader( $module, 'format' );
731 $msg2 = $module->makeHelpMsg();
732 if ( $msg2 !== false ) {
733 $msg .= $msg2;
734 }
735 $msg .= "\n";
736 }
737
738 $msg .= "\n*** Credits: ***\n " . implode( "\n ", $this->getCredits() ) . "\n";
739
740
741 return $msg;
742 }
743
744 public static function makeHelpMsgHeader( $module, $paramName ) {
745 $modulePrefix = $module->getModulePrefix();
746 if ( strval( $modulePrefix ) !== '' ) {
747 $modulePrefix = "($modulePrefix) ";
748 }
749
750 return "* $paramName={$module->getModuleName()} $modulePrefix*";
751 }
752
753 private $mIsBot = null;
754 private $mIsSysop = null;
755 private $mCanApiHighLimits = null;
756
757 /**
758 * Returns true if the currently logged in user is a bot, false otherwise
759 * OBSOLETE, use canApiHighLimits() instead
760 */
761 public function isBot() {
762 if ( !isset( $this->mIsBot ) ) {
763 global $wgUser;
764 $this->mIsBot = $wgUser->isAllowed( 'bot' );
765 }
766 return $this->mIsBot;
767 }
768
769 /**
770 * Similar to isBot(), this method returns true if the logged in user is
771 * a sysop, and false if not.
772 * OBSOLETE, use canApiHighLimits() instead
773 */
774 public function isSysop() {
775 if ( !isset( $this->mIsSysop ) ) {
776 global $wgUser;
777 $this->mIsSysop = in_array( 'sysop', $wgUser->getGroups() );
778 }
779
780 return $this->mIsSysop;
781 }
782
783 /**
784 * Check whether the current user is allowed to use high limits
785 * @return bool
786 */
787 public function canApiHighLimits() {
788 if ( !isset( $this->mCanApiHighLimits ) ) {
789 global $wgUser;
790 $this->mCanApiHighLimits = $wgUser->isAllowed( 'apihighlimits' );
791 }
792
793 return $this->mCanApiHighLimits;
794 }
795
796 /**
797 * Check whether the user wants us to show version information in the API help
798 * @return bool
799 */
800 public function getShowVersions() {
801 return $this->mShowVersions;
802 }
803
804 /**
805 * Returns the version information of this file, plus it includes
806 * the versions for all files that are not callable proper API modules
807 */
808 public function getVersion() {
809 $vers = array ();
810 $vers[] = 'MediaWiki: ' . SpecialVersion::getVersion() . "\n http://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/";
811 $vers[] = __CLASS__ . ': $Id$';
812 $vers[] = ApiBase::getBaseVersion();
813 $vers[] = ApiFormatBase::getBaseVersion();
814 $vers[] = ApiQueryBase::getBaseVersion();
815 return $vers;
816 }
817
818 /**
819 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
820 * classes who wish to add their own modules to their lexicon or override the
821 * behavior of inherent ones.
822 *
823 * @param $mdlName String The identifier for this module.
824 * @param $mdlClass String The class where this module is implemented.
825 */
826 protected function addModule( $mdlName, $mdlClass ) {
827 $this->mModules[$mdlName] = $mdlClass;
828 }
829
830 /**
831 * Add or overwrite an output format for this ApiMain. Intended for use by extending
832 * classes who wish to add to or modify current formatters.
833 *
834 * @param $fmtName The identifier for this format.
835 * @param $fmtClass The class implementing this format.
836 */
837 protected function addFormat( $fmtName, $fmtClass ) {
838 $this->mFormats[$fmtName] = $fmtClass;
839 }
840
841 /**
842 * Get the array mapping module names to class names
843 */
844 function getModules() {
845 return $this->mModules;
846 }
847 }
848
849 /**
850 * This exception will be thrown when dieUsage is called to stop module execution.
851 * The exception handling code will print a help screen explaining how this API may be used.
852 *
853 * @ingroup API
854 */
855 class UsageException extends Exception {
856
857 private $mCodestr;
858 private $mExtraData;
859
860 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
861 parent::__construct( $message, $code );
862 $this->mCodestr = $codestr;
863 $this->mExtraData = $extradata;
864 }
865
866 public function getCodeString() {
867 return $this->mCodestr;
868 }
869
870 public function getMessageArray() {
871 $result = array(
872 'code' => $this->mCodestr,
873 'info' => $this->getMessage()
874 );
875 if ( is_array( $this->mExtraData ) ) {
876 $result = array_merge( $result, $this->mExtraData );
877 }
878 return $result;
879 }
880
881 public function __toString() {
882 return "{$this->getCodeString()}: {$this->getMessage()}";
883 }
884 }