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