API: Changing all modules' getParamDescription(), getAllowedParams() and getDescripti...
[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 * This is the main API class, used for both external and internal processing.
33 * When executed, it will create the requested formatter object,
34 * instantiate and execute an object associated with the needed action,
35 * and use formatter to print results.
36 * In case of an exception, an error message will be printed using the same formatter.
37 *
38 * To use API from another application, run it using FauxRequest object, in which
39 * case any internal exceptions will not be handled but passed up to the caller.
40 * After successful execution, use getResult() for the resulting data.
41 *
42 * @addtogroup API
43 */
44 class ApiMain extends ApiBase {
45
46 /**
47 * When no format parameter is given, this format will be used
48 */
49 const API_DEFAULT_FORMAT = 'xmlfm';
50
51 /**
52 * List of available modules: action name => module class
53 */
54 private static $Modules = array (
55 'login' => 'ApiLogin',
56 'logout' => 'ApiLogout',
57 'query' => 'ApiQuery',
58 'expandtemplates' => 'ApiExpandTemplates',
59 'parse' => 'ApiParse',
60 'opensearch' => 'ApiOpenSearch',
61 'feedwatchlist' => 'ApiFeedWatchlist',
62 'help' => 'ApiHelp',
63 'paraminfo' => 'ApiParamInfo',
64 );
65
66 private static $WriteModules = array (
67 'rollback' => 'ApiRollback',
68 'delete' => 'ApiDelete',
69 'undelete' => 'ApiUndelete',
70 'protect' => 'ApiProtect',
71 'block' => 'ApiBlock',
72 'unblock' => 'ApiUnblock',
73 'move' => 'ApiMove',
74 #'changerights' => 'ApiChangeRights'
75 # Disabled for now
76 );
77
78 /**
79 * List of available formats: format name => format class
80 */
81 private static $Formats = array (
82 'json' => 'ApiFormatJson',
83 'jsonfm' => 'ApiFormatJson',
84 'php' => 'ApiFormatPhp',
85 'phpfm' => 'ApiFormatPhp',
86 'wddx' => 'ApiFormatWddx',
87 'wddxfm' => 'ApiFormatWddx',
88 'xml' => 'ApiFormatXml',
89 'xmlfm' => 'ApiFormatXml',
90 'yaml' => 'ApiFormatYaml',
91 'yamlfm' => 'ApiFormatYaml',
92 'rawfm' => 'ApiFormatJson',
93 'txt' => 'ApiFormatTxt',
94 'txtfm' => 'ApiFormatTxt',
95 'dbg' => 'ApiFormatDbg',
96 'dbgfm' => 'ApiFormatDbg'
97 );
98
99 private $mPrinter, $mModules, $mModuleNames, $mFormats, $mFormatNames;
100 private $mResult, $mAction, $mShowVersions, $mEnableWrite, $mRequest, $mInternalMode, $mSquidMaxage;
101
102 /**
103 * Constructs an instance of ApiMain that utilizes the module and format specified by $request.
104 *
105 * @param $request object - if this is an instance of FauxRequest, errors are thrown and no printing occurs
106 * @param $enableWrite bool should be set to true if the api may modify data
107 */
108 public function __construct($request, $enableWrite = false) {
109
110 $this->mInternalMode = ($request instanceof FauxRequest);
111
112 // Special handling for the main module: $parent === $this
113 parent :: __construct($this, $this->mInternalMode ? 'main_int' : 'main');
114
115 if (!$this->mInternalMode) {
116
117 // Impose module restrictions.
118 // If the current user cannot read,
119 // Remove all modules other than login
120 global $wgUser;
121 if (!$wgUser->isAllowed('read')) {
122 self::$Modules = array(
123 'login' => self::$Modules['login'],
124 'logout' => self::$Modules['logout'],
125 'help' => self::$Modules['help'],
126 );
127 }
128 }
129
130 global $wgAPIModules, $wgEnableWriteAPI; // extension modules
131 $this->mModules = $wgAPIModules + self :: $Modules;
132 if($wgEnableWriteAPI)
133 $this->mModules += self::$WriteModules;
134
135 $this->mModuleNames = array_keys($this->mModules); // todo: optimize
136 $this->mFormats = self :: $Formats;
137 $this->mFormatNames = array_keys($this->mFormats); // todo: optimize
138
139 $this->mResult = new ApiResult($this);
140 $this->mShowVersions = false;
141 $this->mEnableWrite = $enableWrite;
142
143 $this->mRequest = & $request;
144
145 $this->mSquidMaxage = 0;
146 }
147
148 /**
149 * Return true if the API was started by other PHP code using FauxRequest
150 */
151 public function isInternalMode() {
152 return $this->mInternalMode;
153 }
154
155 /**
156 * Return the request object that contains client's request
157 */
158 public function getRequest() {
159 return $this->mRequest;
160 }
161
162 /**
163 * Get the ApiResult object asscosiated with current request
164 */
165 public function getResult() {
166 return $this->mResult;
167 }
168
169 /**
170 * This method will simply cause an error if the write mode was disabled for this api.
171 */
172 public function requestWriteMode() {
173 if (!$this->mEnableWrite)
174 $this->dieUsage('Editing of this site is disabled. Make sure the $wgEnableWriteAPI=true; ' .
175 'statement is included in the site\'s LocalSettings.php file', 'noapiwrite');
176 }
177
178 /**
179 * Set how long the response should be cached.
180 */
181 public function setCacheMaxAge($maxage) {
182 $this->mSquidMaxage = $maxage;
183 }
184
185 /**
186 * Create an instance of an output formatter by its name
187 */
188 public function createPrinterByName($format) {
189 return new $this->mFormats[$format] ($this, $format);
190 }
191
192 /**
193 * Execute api request. Any errors will be handled if the API was called by the remote client.
194 */
195 public function execute() {
196 $this->profileIn();
197 if ($this->mInternalMode)
198 $this->executeAction();
199 else
200 $this->executeActionWithErrorHandling();
201 $this->profileOut();
202 }
203
204 /**
205 * Execute an action, and in case of an error, erase whatever partial results
206 * have been accumulated, and replace it with an error message and a help screen.
207 */
208 protected function executeActionWithErrorHandling() {
209
210 // In case an error occurs during data output,
211 // clear the output buffer and print just the error information
212 ob_start();
213
214 try {
215 $this->executeAction();
216 } catch (Exception $e) {
217 //
218 // Handle any kind of exception by outputing properly formatted error message.
219 // If this fails, an unhandled exception should be thrown so that global error
220 // handler will process and log it.
221 //
222
223 $errCode = $this->substituteResultWithError($e);
224
225 // Error results should not be cached
226 $this->setCacheMaxAge(0);
227
228 $headerStr = 'MediaWiki-API-Error: ' . $errCode;
229 if ($e->getCode() === 0)
230 header($headerStr, true);
231 else
232 header($headerStr, true, $e->getCode());
233
234 // Reset and print just the error message
235 ob_clean();
236
237 // If the error occured during printing, do a printer->profileOut()
238 $this->mPrinter->safeProfileOut();
239 $this->printResult(true);
240 }
241
242 // Set the cache expiration at the last moment, as any errors may change the expiration.
243 // if $this->mSquidMaxage == 0, the expiry time is set to the first second of unix epoch
244 $expires = $this->mSquidMaxage == 0 ? 1 : time() + $this->mSquidMaxage;
245 header('Expires: ' . wfTimestamp(TS_RFC2822, $expires));
246 header('Cache-Control: s-maxage=' . $this->mSquidMaxage . ', must-revalidate, max-age=0');
247
248 if($this->mPrinter->getIsHtml())
249 echo wfReportTime();
250
251 ob_end_flush();
252 }
253
254 /**
255 * Replace the result data with the information about an exception.
256 * Returns the error code
257 */
258 protected function substituteResultWithError($e) {
259
260 // Printer may not be initialized if the extractRequestParams() fails for the main module
261 if (!isset ($this->mPrinter)) {
262 // The printer has not been created yet. Try to manually get formatter value.
263 $value = $this->getRequest()->getVal('format', self::API_DEFAULT_FORMAT);
264 if (!in_array($value, $this->mFormatNames))
265 $value = self::API_DEFAULT_FORMAT;
266
267 $this->mPrinter = $this->createPrinterByName($value);
268 if ($this->mPrinter->getNeedsRawData())
269 $this->getResult()->setRawMode();
270 }
271
272 if ($e instanceof UsageException) {
273 //
274 // User entered incorrect parameters - print usage screen
275 //
276 $errMessage = array (
277 'code' => $e->getCodeString(),
278 'info' => $e->getMessage());
279
280 // Only print the help message when this is for the developer, not runtime
281 if ($this->mPrinter->getIsHtml() || $this->mAction == 'help')
282 ApiResult :: setContent($errMessage, $this->makeHelpMsg());
283
284 } else {
285 //
286 // Something is seriously wrong
287 //
288 $errMessage = array (
289 'code' => 'internal_api_error_'. get_class($e),
290 'info' => "Exception Caught: {$e->getMessage()}"
291 );
292 ApiResult :: setContent($errMessage, "\n\n{$e->getTraceAsString()}\n\n");
293 }
294
295 $this->getResult()->reset();
296 $this->getResult()->addValue(null, 'error', $errMessage);
297
298 return $errMessage['code'];
299 }
300
301 /**
302 * Execute the actual module, without any error handling
303 */
304 protected function executeAction() {
305
306 $params = $this->extractRequestParams();
307
308 $this->mShowVersions = $params['version'];
309 $this->mAction = $params['action'];
310
311 // Instantiate the module requested by the user
312 $module = new $this->mModules[$this->mAction] ($this, $this->mAction);
313
314 if( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
315 // Check for maxlag
316 global $wgLoadBalancer, $wgShowHostnames;
317 $maxLag = $params['maxlag'];
318 list( $host, $lag ) = $wgLoadBalancer->getMaxLag();
319 if ( $lag > $maxLag ) {
320 if( $wgShowHostnames ) {
321 ApiBase :: dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
322 } else {
323 ApiBase :: dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
324 }
325 return;
326 }
327 }
328
329 if (!$this->mInternalMode) {
330 // Ignore mustBePosted() for internal calls
331 if($module->mustBePosted() && !$this->mRequest->wasPosted())
332 $this->dieUsage("The {$this->mAction} module requires a POST request", 'mustbeposted');
333
334 // See if custom printer is used
335 $this->mPrinter = $module->getCustomPrinter();
336 if (is_null($this->mPrinter)) {
337 // Create an appropriate printer
338 $this->mPrinter = $this->createPrinterByName($params['format']);
339 }
340
341 if ($this->mPrinter->getNeedsRawData())
342 $this->getResult()->setRawMode();
343 }
344
345 // Execute
346 $module->profileIn();
347 $module->execute();
348 $module->profileOut();
349
350 if (!$this->mInternalMode) {
351 // Print result data
352 $this->printResult(false);
353 }
354 }
355
356 /**
357 * Print results using the current printer
358 */
359 protected function printResult($isError) {
360 $printer = $this->mPrinter;
361 $printer->profileIn();
362
363 /* If the help message is requested in the default (xmlfm) format,
364 * tell the printer not to escape ampersands so that our links do
365 * not break. */
366 $params = $this->extractRequestParams();
367 $printer->setUnescapeAmps ( ( $this->mAction == 'help' || $isError )
368 && $params['format'] == ApiMain::API_DEFAULT_FORMAT );
369
370 $printer->initPrinter($isError);
371
372 $printer->execute();
373 $printer->closePrinter();
374 $printer->profileOut();
375 }
376
377 /**
378 * See ApiBase for description.
379 */
380 public function getAllowedParams() {
381 return array (
382 'format' => array (
383 ApiBase :: PARAM_DFLT => ApiMain :: API_DEFAULT_FORMAT,
384 ApiBase :: PARAM_TYPE => $this->mFormatNames
385 ),
386 'action' => array (
387 ApiBase :: PARAM_DFLT => 'help',
388 ApiBase :: PARAM_TYPE => $this->mModuleNames
389 ),
390 'version' => false,
391 'maxlag' => array (
392 ApiBase :: PARAM_TYPE => 'integer'
393 ),
394 );
395 }
396
397 /**
398 * See ApiBase for description.
399 */
400 public function getParamDescription() {
401 return array (
402 'format' => 'The format of the output',
403 'action' => 'What action you would like to perform',
404 'version' => 'When showing help, include version for each module',
405 'maxlag' => 'Maximum lag'
406 );
407 }
408
409 /**
410 * See ApiBase for description.
411 */
412 public function getDescription() {
413 return array (
414 '',
415 '',
416 '******************************************************************',
417 '** **',
418 '** This is an auto-generated MediaWiki API documentation page **',
419 '** **',
420 '** Documentation and Examples: **',
421 '** http://www.mediawiki.org/wiki/API **',
422 '** **',
423 '******************************************************************',
424 '',
425 'Status: All features shown on this page should be working, but the API',
426 ' is still in active development, and may change at any time.',
427 ' Make sure to monitor our mailing list for any updates.',
428 '',
429 'Documentation: http://www.mediawiki.org/wiki/API',
430 'Mailing list: http://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
431 'Bugs & Requests: http://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
432 '',
433 '',
434 '',
435 '',
436 '',
437 );
438 }
439
440 /**
441 * Returns an array of strings with credits for the API
442 */
443 protected function getCredits() {
444 return array(
445 'This API is being implemented by Yuri Astrakhan [[User:Yurik]] / <Firstname><Lastname>@gmail.com',
446 'Please leave your comments and suggestions at http://www.mediawiki.org/wiki/API'
447 );
448 }
449
450 /**
451 * Override the parent to generate help messages for all available modules.
452 */
453 public function makeHelpMsg() {
454
455 $this->mPrinter->setHelp();
456
457 // Use parent to make default message for the main module
458 $msg = parent :: makeHelpMsg();
459
460 $astriks = str_repeat('*** ', 10);
461 $msg .= "\n\n$astriks Modules $astriks\n\n";
462 foreach( $this->mModules as $moduleName => $unused ) {
463 $module = new $this->mModules[$moduleName] ($this, $moduleName);
464 $msg .= self::makeHelpMsgHeader($module, 'action');
465 $msg2 = $module->makeHelpMsg();
466 if ($msg2 !== false)
467 $msg .= $msg2;
468 $msg .= "\n";
469 }
470
471 $msg .= "\n$astriks Formats $astriks\n\n";
472 foreach( $this->mFormats as $formatName => $unused ) {
473 $module = $this->createPrinterByName($formatName);
474 $msg .= self::makeHelpMsgHeader($module, 'format');
475 $msg2 = $module->makeHelpMsg();
476 if ($msg2 !== false)
477 $msg .= $msg2;
478 $msg .= "\n";
479 }
480
481 $msg .= "\n*** Credits: ***\n " . implode("\n ", $this->getCredits()) . "\n";
482
483
484 return $msg;
485 }
486
487 public static function makeHelpMsgHeader($module, $paramName) {
488 $modulePrefix = $module->getModulePrefix();
489 if (!empty($modulePrefix))
490 $modulePrefix = "($modulePrefix) ";
491
492 return "* $paramName={$module->getModuleName()} $modulePrefix*";
493 }
494
495 private $mIsBot = null;
496 private $mIsSysop = null;
497 private $mCanApiHighLimits = null;
498
499 /**
500 * Returns true if the currently logged in user is a bot, false otherwise
501 * OBSOLETE, use canApiHighLimits() instead
502 */
503 public function isBot() {
504 if (!isset ($this->mIsBot)) {
505 global $wgUser;
506 $this->mIsBot = $wgUser->isAllowed('bot');
507 }
508 return $this->mIsBot;
509 }
510
511 /**
512 * Similar to isBot(), this method returns true if the logged in user is
513 * a sysop, and false if not.
514 * OBSOLETE, use canApiHighLimits() instead
515 */
516 public function isSysop() {
517 if (!isset ($this->mIsSysop)) {
518 global $wgUser;
519 $this->mIsSysop = in_array( 'sysop', $wgUser->getGroups());
520 }
521
522 return $this->mIsSysop;
523 }
524
525 public function canApiHighLimits() {
526 if (!isset($this->mCanApiHighLimits)) {
527 global $wgUser;
528 $this->mCanApiHighLimits = $wgUser->isAllowed('apihighlimits');
529 }
530
531 return $this->mCanApiHighLimits;
532 }
533
534 public function getShowVersions() {
535 return $this->mShowVersions;
536 }
537
538 /**
539 * Returns the version information of this file, plus it includes
540 * the versions for all files that are not callable proper API modules
541 */
542 public function getVersion() {
543 $vers = array ();
544 $vers[] = 'MediaWiki ' . SpecialVersion::getVersion();
545 $vers[] = __CLASS__ . ': $Id$';
546 $vers[] = ApiBase :: getBaseVersion();
547 $vers[] = ApiFormatBase :: getBaseVersion();
548 $vers[] = ApiQueryBase :: getBaseVersion();
549 $vers[] = ApiFormatFeedWrapper :: getVersion(); // not accessible with format=xxx
550 return $vers;
551 }
552
553 /**
554 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
555 * classes who wish to add their own modules to their lexicon or override the
556 * behavior of inherent ones.
557 *
558 * @access protected
559 * @param $mdlName String The identifier for this module.
560 * @param $mdlClass String The class where this module is implemented.
561 */
562 protected function addModule( $mdlName, $mdlClass ) {
563 $this->mModules[$mdlName] = $mdlClass;
564 }
565
566 /**
567 * Add or overwrite an output format for this ApiMain. Intended for use by extending
568 * classes who wish to add to or modify current formatters.
569 *
570 * @access protected
571 * @param $fmtName The identifier for this format.
572 * @param $fmtClass The class implementing this format.
573 */
574 protected function addFormat( $fmtName, $fmtClass ) {
575 $this->mFormats[$fmtName] = $fmtClass;
576 }
577
578 /**
579 * Get the array mapping module names to class names
580 */
581 function getModules() {
582 return $this->mModules;
583 }
584 }
585
586 /**
587 * This exception will be thrown when dieUsage is called to stop module execution.
588 * The exception handling code will print a help screen explaining how this API may be used.
589 *
590 * @addtogroup API
591 */
592 class UsageException extends Exception {
593
594 private $mCodestr;
595
596 public function __construct($message, $codestr, $code = 0) {
597 parent :: __construct($message, $code);
598 $this->mCodestr = $codestr;
599 }
600 public function getCodeString() {
601 return $this->mCodestr;
602 }
603 public function __toString() {
604 return "{$this->getCodeString()}: {$this->getMessage()}";
605 }
606 }
607
608