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