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