b450934a81ed95096b50ae5cdf6504ca28df1426
[lhc/web/wiklou.git] / includes / api / ApiMain.php
1 <?php
2
3 /*
4 * Created on Sep 4, 2006
5 *
6 * API for MediaWiki 1.8+
7 *
8 * Copyright (C) 2006 Yuri Astrakhan <Firstname><Lastname>@gmail.com
9 *
10 * This program is free software; you can redistribute it and/or modify
11 * it under the terms of the GNU General Public License as published by
12 * the Free Software Foundation; either version 2 of the License, or
13 * (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License along
21 * with this program; if not, write to the Free Software Foundation, Inc.,
22 * 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
23 * http://www.gnu.org/copyleft/gpl.html
24 */
25
26 if ( !defined( 'MEDIAWIKI' ) ) {
27 // Eclipse helper - will be ignored in production
28 require_once ( 'ApiBase.php' );
29 }
30
31 /**
32 * @defgroup API API
33 */
34
35 /**
36 * This is the main API class, used for both external and internal processing.
37 * When executed, it will create the requested formatter object,
38 * instantiate and execute an object associated with the needed action,
39 * and use formatter to print results.
40 * In case of an exception, an error message will be printed using the same formatter.
41 *
42 * To use API from another application, run it using FauxRequest object, in which
43 * case any internal exceptions will not be handled but passed up to the caller.
44 * After successful execution, use getResult() for the resulting data.
45 *
46 * @ingroup API
47 */
48 class ApiMain extends ApiBase {
49
50 /**
51 * When no format parameter is given, this format will be used
52 */
53 const API_DEFAULT_FORMAT = 'xmlfm';
54
55 /**
56 * List of available modules: action name => module class
57 */
58 private static $Modules = array (
59 'login' => 'ApiLogin',
60 'logout' => 'ApiLogout',
61 'query' => 'ApiQuery',
62 'expandtemplates' => 'ApiExpandTemplates',
63 'parse' => 'ApiParse',
64 'opensearch' => 'ApiOpenSearch',
65 'feedwatchlist' => 'ApiFeedWatchlist',
66 'help' => 'ApiHelp',
67 'paraminfo' => 'ApiParamInfo',
68
69 // Write modules
70 'purge' => 'ApiPurge',
71 'rollback' => 'ApiRollback',
72 'delete' => 'ApiDelete',
73 'undelete' => 'ApiUndelete',
74 'protect' => 'ApiProtect',
75 'block' => 'ApiBlock',
76 'unblock' => 'ApiUnblock',
77 'move' => 'ApiMove',
78 'edit' => 'ApiEditPage',
79 'upload' => 'ApiUpload',
80 'emailuser' => 'ApiEmailUser',
81 'watch' => 'ApiWatch',
82 'patrol' => 'ApiPatrol',
83 'import' => 'ApiImport',
84 'userrights' => 'ApiUserrights',
85 );
86
87 /**
88 * List of available formats: format name => format class
89 */
90 private static $Formats = array (
91 'json' => 'ApiFormatJson',
92 'jsonfm' => 'ApiFormatJson',
93 'php' => 'ApiFormatPhp',
94 'phpfm' => 'ApiFormatPhp',
95 'wddx' => 'ApiFormatWddx',
96 'wddxfm' => 'ApiFormatWddx',
97 'xml' => 'ApiFormatXml',
98 'xmlfm' => 'ApiFormatXml',
99 'yaml' => 'ApiFormatYaml',
100 'yamlfm' => 'ApiFormatYaml',
101 'rawfm' => 'ApiFormatJson',
102 'txt' => 'ApiFormatTxt',
103 'txtfm' => 'ApiFormatTxt',
104 'dbg' => 'ApiFormatDbg',
105 'dbgfm' => 'ApiFormatDbg'
106 );
107
108 /**
109 * List of user roles that are specifically relevant to the API.
110 * array( 'right' => array ( 'msg' => 'Some message with a $1',
111 * 'params' => array ( $someVarToSubst ) ),
112 * );
113 */
114 private static $mRights = array( 'writeapi' => array(
115 'msg' => 'Use of the write API',
116 'params' => array()
117 ),
118 'apihighlimits' => array(
119 'msg' => 'Use higher limits in API queries (Slow queries: $1 results; Fast queries: $2 results). The limits for slow queries also apply to multivalue parameters.',
120 'params' => array ( ApiMain::LIMIT_SML2, ApiMain::LIMIT_BIG2 )
121 )
122 );
123
124
125 private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
126 private $mResult, $mAction, $mShowVersions, $mEnableWrite, $mRequest;
127 private $mInternalMode, $mSquidMaxage, $mModule;
128
129 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
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
146 // Impose module restrictions.
147 // If the current user cannot read,
148 // Remove all modules other than login
149 global $wgUser;
150
151 if ( $request->getVal( 'callback' ) !== null ) {
152 // JSON callback allows cross-site reads.
153 // For safety, strip user credentials.
154 wfDebug( "API: stripping user credentials for JSON callback\n" );
155 $wgUser = new User();
156 }
157 }
158
159 global $wgAPIModules; // extension modules
160 $this->mModules = $wgAPIModules + self :: $Modules;
161
162 $this->mModuleNames = array_keys( $this->mModules );
163 $this->mFormats = self :: $Formats;
164 $this->mFormatNames = array_keys( $this->mFormats );
165
166 $this->mResult = new ApiResult( $this );
167 $this->mShowVersions = false;
168 $this->mEnableWrite = $enableWrite;
169
170 $this->mRequest = & $request;
171
172 $this->mSquidMaxage = - 1; // flag for executeActionWithErrorHandling()
173 $this->mCommit = false;
174 }
175
176 /**
177 * Return true if the API was started by other PHP code using FauxRequest
178 */
179 public function isInternalMode() {
180 return $this->mInternalMode;
181 }
182
183 /**
184 * Return the request object that contains client's request
185 */
186 public function getRequest() {
187 return $this->mRequest;
188 }
189
190 /**
191 * Get the ApiResult object associated with current request
192 */
193 public function getResult() {
194 return $this->mResult;
195 }
196
197 /**
198 * Get the API module object. Only works after executeAction()
199 */
200 public function getModule() {
201 return $this->mModule;
202 }
203
204 /**
205 * Only kept for backwards compatibility
206 * @deprecated Use isWriteMode() instead
207 */
208 public function requestWriteMode() {
209 if ( !$this->mEnableWrite )
210 $this->dieUsageMsg( array( 'writedisabled' ) );
211 if ( wfReadOnly() )
212 $this->dieUsageMsg( array( 'readonlytext' ) );
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 return new $this->mFormats[$format] ( $this, $format );
241 }
242
243 /**
244 * Execute api request. Any errors will be handled if the API was called by the remote client.
245 */
246 public function execute() {
247 $this->profileIn();
248 if ( $this->mInternalMode )
249 $this->executeAction();
250 else
251 $this->executeActionWithErrorHandling();
252
253 $this->profileOut();
254 }
255
256 /**
257 * Execute an action, and in case of an error, erase whatever partial results
258 * have been accumulated, and replace it with an error message and a help screen.
259 */
260 protected function executeActionWithErrorHandling() {
261
262 // In case an error occurs during data output,
263 // clear the output buffer and print just the error information
264 ob_start();
265
266 try {
267 $this->executeAction();
268 } catch ( Exception $e ) {
269 // Log it
270 if ( $e instanceof MWException ) {
271 wfDebugLog( 'exception', $e->getLogMessage() );
272 }
273
274 //
275 // Handle any kind of exception by outputing properly formatted error message.
276 // If this fails, an unhandled exception should be thrown so that global error
277 // handler will process and log it.
278 //
279
280 $errCode = $this->substituteResultWithError( $e );
281
282 // Error results should not be cached
283 $this->setCacheMaxAge( 0 );
284
285 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
286 if ( $e->getCode() === 0 )
287 header( $headerStr );
288 else
289 header( $headerStr, true, $e->getCode() );
290
291 // Reset and print just the error message
292 ob_clean();
293
294 // If the error occured during printing, do a printer->profileOut()
295 $this->mPrinter->safeProfileOut();
296 $this->printResult( true );
297 }
298
299 // If nobody called setCacheMaxAge(), use the (s)maxage parameters
300 if ( !isset( $this->mCacheControl['s-maxage'] ) ) {
301 $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' );
302 }
303 if ( !isset( $this->mCacheControl['max-age'] ) ) {
304 $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' );
305 }
306
307 // Set the cache expiration at the last moment, as any errors may change the expiration.
308 // if $this->mSquidMaxage == 0, the expiry time is set to the first second of unix epoch
309 $exp = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] );
310 $expires = ( $exp == 0 ? 1 : time() + $exp );
311 header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expires ) );
312
313 // Construct the Cache-Control header
314 $ccHeader = '';
315 $separator = '';
316 foreach ( $this->mCacheControl as $name => $value ) {
317 if ( is_bool( $value ) ) {
318 if ( $value ) {
319 $ccHeader .= $separator . $name;
320 $separator = ', ';
321 }
322 } else {
323 $ccHeader .= $separator . "$name=$value";
324 $separator = ', ';
325 }
326 }
327
328 header( "Cache-Control: $ccHeader" );
329
330 if ( $this->mPrinter->getIsHtml() )
331 echo wfReportTime();
332
333 ob_end_flush();
334 }
335
336 /**
337 * Replace the result data with the information about an exception.
338 * Returns the error code
339 */
340 protected function substituteResultWithError( $e ) {
341
342 // Printer may not be initialized if the extractRequestParams() fails for the main module
343 if ( !isset ( $this->mPrinter ) ) {
344 // The printer has not been created yet. Try to manually get formatter value.
345 $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT );
346 if ( !in_array( $value, $this->mFormatNames ) )
347 $value = self::API_DEFAULT_FORMAT;
348
349 $this->mPrinter = $this->createPrinterByName( $value );
350 if ( $this->mPrinter->getNeedsRawData() )
351 $this->getResult()->setRawMode();
352 }
353
354 if ( $e instanceof UsageException ) {
355 //
356 // User entered incorrect parameters - print usage screen
357 //
358 $errMessage = $e->getMessageArray();
359
360 // Only print the help message when this is for the developer, not runtime
361 if ( $this->mPrinter->getWantsHelp() || $this->mAction == 'help' )
362 ApiResult :: setContent( $errMessage, $this->makeHelpMsg() );
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 $this->getResult()->addValue( null, 'error', $errMessage );
389
390 return $errMessage['code'];
391 }
392
393 /**
394 * Execute the actual module, without any error handling
395 */
396 protected function executeAction() {
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 $params = $this->extractRequestParams();
403
404 $this->mShowVersions = $params['version'];
405 $this->mAction = $params['action'];
406
407 if ( !is_string( $this->mAction ) ) {
408 $this->dieUsage( "The API requires a valid action parameter", 'unknown_action' );
409 }
410
411 // Instantiate the module requested by the user
412 $module = new $this->mModules[$this->mAction] ( $this, $this->mAction );
413 $this->mModule = $module;
414
415 $moduleParams = $module->extractRequestParams();
416
417 // Die if token required, but not provided (unless there is a gettoken parameter)
418 $salt = $module->getTokenSalt();
419 if ( $salt !== false && !isset( $moduleParams['gettoken'] ) )
420 {
421 if ( !isset( $moduleParams['token'] ) ) {
422 $this->dieUsageMsg( array( 'missingparam', 'token' ) );
423 } else {
424 global $wgUser;
425 if ( !$wgUser->matchEditToken( $moduleParams['token'], $salt ) ) {
426 $this->dieUsageMsg( array( 'sessionfailure' ) );
427 }
428 }
429 }
430
431 if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
432 // Check for maxlag
433 global $wgShowHostnames;
434 $maxLag = $params['maxlag'];
435 list( $host, $lag ) = wfGetLB()->getMaxLag();
436 if ( $lag > $maxLag ) {
437 header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) );
438 header( 'X-Database-Lag: ' . intval( $lag ) );
439 if ( $wgShowHostnames ) {
440 $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
441 } else {
442 $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
443 }
444 return;
445 }
446 }
447
448 global $wgUser, $wgGroupPermissions;
449 if ( $module->isReadMode() && !$wgGroupPermissions['*']['read'] && !$wgUser->isAllowed( 'read' ) )
450 $this->dieUsageMsg( array( 'readrequired' ) );
451 if ( $module->isWriteMode() ) {
452 if ( !$this->mEnableWrite )
453 $this->dieUsageMsg( array( 'writedisabled' ) );
454 if ( !$wgUser->isAllowed( 'writeapi' ) )
455 $this->dieUsageMsg( array( 'writerequired' ) );
456 if ( wfReadOnly() )
457 $this->dieReadOnly();
458 }
459
460 if ( !$this->mInternalMode ) {
461 // Ignore mustBePosted() for internal calls
462 if ( $module->mustBePosted() && !$this->mRequest->wasPosted() )
463 $this->dieUsageMsg( array ( 'mustbeposted', $this->mAction ) );
464
465 // See if custom printer is used
466 $this->mPrinter = $module->getCustomPrinter();
467 if ( is_null( $this->mPrinter ) ) {
468 // Create an appropriate printer
469 $this->mPrinter = $this->createPrinterByName( $params['format'] );
470 }
471
472 if ( $this->mPrinter->getNeedsRawData() )
473 $this->getResult()->setRawMode();
474 }
475
476 // Execute
477 $module->profileIn();
478 $module->execute();
479 wfRunHooks( 'APIAfterExecute', array( &$module ) );
480 $module->profileOut();
481
482 if ( !$this->mInternalMode ) {
483 // Print result data
484 $this->printResult( false );
485 }
486 }
487
488 /**
489 * Print results using the current printer
490 */
491 protected function printResult( $isError ) {
492 $this->getResult()->cleanUpUTF8();
493 $printer = $this->mPrinter;
494 $printer->profileIn();
495
496 /* If the help message is requested in the default (xmlfm) format,
497 * tell the printer not to escape ampersands so that our links do
498 * not break. */
499 $printer->setUnescapeAmps ( ( $this->mAction == 'help' || $isError )
500 && $printer->getFormat() == 'XML' && $printer->getIsHtml() );
501
502 $printer->initPrinter( $isError );
503
504 $printer->execute();
505 $printer->closePrinter();
506 $printer->profileOut();
507 }
508
509 public function isReadMode() {
510 return false;
511 }
512
513 /**
514 * See ApiBase for description.
515 */
516 public function getAllowedParams() {
517 return array (
518 'format' => array (
519 ApiBase :: PARAM_DFLT => ApiMain :: API_DEFAULT_FORMAT,
520 ApiBase :: PARAM_TYPE => $this->mFormatNames
521 ),
522 'action' => array (
523 ApiBase :: PARAM_DFLT => 'help',
524 ApiBase :: PARAM_TYPE => $this->mModuleNames
525 ),
526 'version' => false,
527 'maxlag' => array (
528 ApiBase :: PARAM_TYPE => 'integer'
529 ),
530 'smaxage' => array (
531 ApiBase :: PARAM_TYPE => 'integer',
532 ApiBase :: PARAM_DFLT => 0
533 ),
534 'maxage' => array (
535 ApiBase :: PARAM_TYPE => 'integer',
536 ApiBase :: PARAM_DFLT => 0
537 ),
538 'requestid' => null,
539 );
540 }
541
542 /**
543 * See ApiBase for description.
544 */
545 public function getParamDescription() {
546 return array (
547 'format' => 'The format of the output',
548 'action' => 'What action you would like to perform',
549 'version' => 'When showing help, include version for each module',
550 'maxlag' => 'Maximum lag',
551 'smaxage' => 'Set the s-maxage header to this many seconds. Errors are never cached',
552 'maxage' => 'Set the max-age header to this many seconds. Errors are never cached',
553 'requestid' => 'Request ID to distinguish requests. This will just be output back to you',
554 );
555 }
556
557 /**
558 * See ApiBase for description.
559 */
560 public function getDescription() {
561 return array (
562 '',
563 '',
564 '******************************************************************',
565 '** **',
566 '** This is an auto-generated MediaWiki API documentation page **',
567 '** **',
568 '** Documentation and Examples: **',
569 '** http://www.mediawiki.org/wiki/API **',
570 '** **',
571 '******************************************************************',
572 '',
573 'Status: All features shown on this page should be working, but the API',
574 ' is still in active development, and may change at any time.',
575 ' Make sure to monitor our mailing list for any updates.',
576 '',
577 'Documentation: http://www.mediawiki.org/wiki/API',
578 'Mailing list: http://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
579 'Bugs & Requests: http://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
580 '',
581 '',
582 '',
583 '',
584 '',
585 );
586 }
587
588 public function getPossibleErrors() {
589 return array_merge( parent::getPossibleErrors(), array(
590 array( 'readonlytext' ),
591 array( 'code' => 'unknown_format', 'info' => 'Unrecognized format: format' ),
592 array( 'code' => 'unknown_action', 'info' => 'The API requires a valid action parameter' ),
593 array( 'code' => 'maxlag', 'info' => 'Waiting for host: x seconds lagged' ),
594 array( 'code' => 'maxlag', 'info' => 'Waiting for a database server: x seconds lagged' ),
595 ) );
596 }
597
598 /**
599 * Returns an array of strings with credits for the API
600 */
601 protected function getCredits() {
602 return array(
603 'API developers:',
604 ' Roan Kattouw <Firstname>.<Lastname>@home.nl (lead developer Sep 2007-present)',
605 ' Victor Vasiliev - vasilvv at gee mail dot com',
606 ' Bryan Tong Minh - bryan . tongminh @ gmail . com',
607 ' Sam Reed - sam @ reedyboy . net',
608 ' Yuri Astrakhan <Firstname><Lastname>@gmail.com (creator, lead developer Sep 2006-Sep 2007)',
609 '',
610 'Please send your comments, suggestions and questions to mediawiki-api@lists.wikimedia.org',
611 'or file a bug report at http://bugzilla.wikimedia.org/'
612 );
613 }
614
615 /**
616 * Override the parent to generate help messages for all available modules.
617 */
618 public function makeHelpMsg() {
619 global $wgMemc, $wgAPICacheHelp, $wgAPICacheHelpTimeout;
620 $this->mPrinter->setHelp();
621 // Get help text from cache if present
622 $key = wfMemcKey( 'apihelp', $this->getModuleName(),
623 SpecialVersion::getVersion( 'nodb' ) .
624 $this->getMain()->getShowVersions() );
625 if ( $wgAPICacheHelp ) {
626 $cached = $wgMemc->get( $key );
627 if ( $cached )
628 return $cached;
629 }
630 $retval = $this->reallyMakeHelpMsg();
631 if ( $wgAPICacheHelp )
632 $wgMemc->set( $key, $retval, $wgAPICacheHelpTimeout );
633 return $retval;
634 }
635
636 public function reallyMakeHelpMsg() {
637
638 $this->mPrinter->setHelp();
639
640 // Use parent to make default message for the main module
641 $msg = parent :: makeHelpMsg();
642
643 $astriks = str_repeat( '*** ', 10 );
644 $msg .= "\n\n$astriks Modules $astriks\n\n";
645 foreach ( $this->mModules as $moduleName => $unused ) {
646 $module = new $this->mModules[$moduleName] ( $this, $moduleName );
647 $msg .= self::makeHelpMsgHeader( $module, 'action' );
648 $msg2 = $module->makeHelpMsg();
649 if ( $msg2 !== false )
650 $msg .= $msg2;
651 $msg .= "\n";
652 }
653
654 $msg .= "\n$astriks Permissions $astriks\n\n";
655 foreach ( self :: $mRights as $right => $rightMsg ) {
656 $groups = User::getGroupsWithPermission( $right );
657 $msg .= "* " . $right . " *\n " . wfMsgReplaceArgs( $rightMsg[ 'msg' ], $rightMsg[ 'params' ] ) .
658 "\nGranted to:\n " . str_replace( "*", "all", implode( ", ", $groups ) ) . "\n";
659
660 }
661
662 $msg .= "\n$astriks Formats $astriks\n\n";
663 foreach ( $this->mFormats as $formatName => $unused ) {
664 $module = $this->createPrinterByName( $formatName );
665 $msg .= self::makeHelpMsgHeader( $module, 'format' );
666 $msg2 = $module->makeHelpMsg();
667 if ( $msg2 !== false )
668 $msg .= $msg2;
669 $msg .= "\n";
670 }
671
672 $msg .= "\n*** Credits: ***\n " . implode( "\n ", $this->getCredits() ) . "\n";
673
674
675 return $msg;
676 }
677
678 public static function makeHelpMsgHeader( $module, $paramName ) {
679 $modulePrefix = $module->getModulePrefix();
680 if ( strval( $modulePrefix ) !== '' )
681 $modulePrefix = "($modulePrefix) ";
682
683 return "* $paramName={$module->getModuleName()} $modulePrefix*";
684 }
685
686 private $mIsBot = null;
687 private $mIsSysop = null;
688 private $mCanApiHighLimits = null;
689
690 /**
691 * Returns true if the currently logged in user is a bot, false otherwise
692 * OBSOLETE, use canApiHighLimits() instead
693 */
694 public function isBot() {
695 if ( !isset ( $this->mIsBot ) ) {
696 global $wgUser;
697 $this->mIsBot = $wgUser->isAllowed( 'bot' );
698 }
699 return $this->mIsBot;
700 }
701
702 /**
703 * Similar to isBot(), this method returns true if the logged in user is
704 * a sysop, and false if not.
705 * OBSOLETE, use canApiHighLimits() instead
706 */
707 public function isSysop() {
708 if ( !isset ( $this->mIsSysop ) ) {
709 global $wgUser;
710 $this->mIsSysop = in_array( 'sysop', $wgUser->getGroups() );
711 }
712
713 return $this->mIsSysop;
714 }
715
716 /**
717 * Check whether the current user is allowed to use high limits
718 * @return bool
719 */
720 public function canApiHighLimits() {
721 if ( !isset( $this->mCanApiHighLimits ) ) {
722 global $wgUser;
723 $this->mCanApiHighLimits = $wgUser->isAllowed( 'apihighlimits' );
724 }
725
726 return $this->mCanApiHighLimits;
727 }
728
729 /**
730 * Check whether the user wants us to show version information in the API help
731 * @return bool
732 */
733 public function getShowVersions() {
734 return $this->mShowVersions;
735 }
736
737 /**
738 * Returns the version information of this file, plus it includes
739 * the versions for all files that are not callable proper API modules
740 */
741 public function getVersion() {
742 $vers = array ();
743 $vers[] = 'MediaWiki: ' . SpecialVersion::getVersion() . "\n http://svn.wikimedia.org/viewvc/mediawiki/trunk/phase3/";
744 $vers[] = __CLASS__ . ': $Id$';
745 $vers[] = ApiBase :: getBaseVersion();
746 $vers[] = ApiFormatBase :: getBaseVersion();
747 $vers[] = ApiQueryBase :: getBaseVersion();
748 return $vers;
749 }
750
751 /**
752 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
753 * classes who wish to add their own modules to their lexicon or override the
754 * behavior of inherent ones.
755 *
756 * @access protected
757 * @param $mdlName String The identifier for this module.
758 * @param $mdlClass String The class where this module is implemented.
759 */
760 protected function addModule( $mdlName, $mdlClass ) {
761 $this->mModules[$mdlName] = $mdlClass;
762 }
763
764 /**
765 * Add or overwrite an output format for this ApiMain. Intended for use by extending
766 * classes who wish to add to or modify current formatters.
767 *
768 * @access protected
769 * @param $fmtName The identifier for this format.
770 * @param $fmtClass The class implementing this format.
771 */
772 protected function addFormat( $fmtName, $fmtClass ) {
773 $this->mFormats[$fmtName] = $fmtClass;
774 }
775
776 /**
777 * Get the array mapping module names to class names
778 */
779 function getModules() {
780 return $this->mModules;
781 }
782 }
783
784 /**
785 * This exception will be thrown when dieUsage is called to stop module execution.
786 * The exception handling code will print a help screen explaining how this API may be used.
787 *
788 * @ingroup API
789 */
790 class UsageException extends Exception {
791
792 private $mCodestr;
793 private $mExtraData;
794
795 public function __construct( $message, $codestr, $code = 0, $extradata = null ) {
796 parent :: __construct( $message, $code );
797 $this->mCodestr = $codestr;
798 $this->mExtraData = $extradata;
799 }
800 public function getCodeString() {
801 return $this->mCodestr;
802 }
803 public function getMessageArray() {
804 $result = array (
805 'code' => $this->mCodestr,
806 'info' => $this->getMessage()
807 );
808 if ( is_array( $this->mExtraData ) )
809 $result = array_merge( $result, $this->mExtraData );
810 return $result;
811 }
812 public function __toString() {
813 return "{$this->getCodeString()}: {$this->getMessage()}";
814 }
815 }