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