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