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