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