* Use *bold* and $italics$ highlighting only in API help. It completely breaks format...
[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 if( $this->mAction == 'help' )
322 $this->mPrinter->setHelp();
323 }
324
325 // Execute
326 $module->profileIn();
327 $module->execute();
328 $module->profileOut();
329
330 if (!$this->mInternalMode) {
331 // Print result data
332 $this->printResult(false);
333 }
334 }
335
336 /**
337 * Print results using the current printer
338 */
339 protected function printResult($isError) {
340 $printer = $this->mPrinter;
341 $printer->profileIn();
342
343 /* If the help message is requested in the default (xmlfm) format,
344 * tell the printer not to escape ampersands so that our links do
345 * not break. */
346 $params = $this->extractRequestParams();
347 $printer->setUnescapeAmps ( ( $this->mAction == 'help' || $isError )
348 && $params['format'] == ApiMain::API_DEFAULT_FORMAT );
349
350 $printer->initPrinter($isError);
351
352 $printer->execute();
353 $printer->closePrinter();
354 $printer->profileOut();
355 }
356
357 /**
358 * See ApiBase for description.
359 */
360 protected function getAllowedParams() {
361 return array (
362 'format' => array (
363 ApiBase :: PARAM_DFLT => ApiMain :: API_DEFAULT_FORMAT,
364 ApiBase :: PARAM_TYPE => $this->mFormatNames
365 ),
366 'action' => array (
367 ApiBase :: PARAM_DFLT => 'help',
368 ApiBase :: PARAM_TYPE => $this->mModuleNames
369 ),
370 'version' => false,
371 'maxlag' => array (
372 ApiBase :: PARAM_TYPE => 'integer'
373 ),
374 );
375 }
376
377 /**
378 * See ApiBase for description.
379 */
380 protected function getParamDescription() {
381 return array (
382 'format' => 'The format of the output',
383 'action' => 'What action you would like to perform',
384 'version' => 'When showing help, include version for each module',
385 'maxlag' => 'Maximum lag'
386 );
387 }
388
389 /**
390 * See ApiBase for description.
391 */
392 protected function getDescription() {
393 return array (
394 '',
395 '',
396 '******************************************************************',
397 '** **',
398 '** This is an auto-generated MediaWiki API documentation page **',
399 '** **',
400 '** Documentation and Examples: **',
401 '** http://www.mediawiki.org/wiki/API **',
402 '** **',
403 '******************************************************************',
404 '',
405 'Status: All features shown on this page should be working, but the API',
406 ' is still in active development, and may change at any time.',
407 ' Make sure to monitor our mailing list for any updates.',
408 '',
409 'Documentation: http://www.mediawiki.org/wiki/API',
410 'Mailing list: http://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
411 'Bugs & Requests: http://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
412 '',
413 '',
414 '',
415 '',
416 '',
417 );
418 }
419
420 /**
421 * Returns an array of strings with credits for the API
422 */
423 protected function getCredits() {
424 return array(
425 'This API is being implemented by Yuri Astrakhan [[User:Yurik]] / <Firstname><Lastname>@gmail.com',
426 'Please leave your comments and suggestions at http://www.mediawiki.org/wiki/API'
427 );
428 }
429
430 /**
431 * Override the parent to generate help messages for all available modules.
432 */
433 public function makeHelpMsg() {
434
435 // Use parent to make default message for the main module
436 $msg = parent :: makeHelpMsg();
437
438 $astriks = str_repeat('*** ', 10);
439 $msg .= "\n\n$astriks Modules $astriks\n\n";
440 foreach( $this->mModules as $moduleName => $unused ) {
441 $module = new $this->mModules[$moduleName] ($this, $moduleName);
442 $msg .= self::makeHelpMsgHeader($module, 'action');
443 $msg2 = $module->makeHelpMsg();
444 if ($msg2 !== false)
445 $msg .= $msg2;
446 $msg .= "\n";
447 }
448
449 $msg .= "\n$astriks Formats $astriks\n\n";
450 foreach( $this->mFormats as $formatName => $unused ) {
451 $module = $this->createPrinterByName($formatName);
452 $msg .= self::makeHelpMsgHeader($module, 'format');
453 $msg2 = $module->makeHelpMsg();
454 if ($msg2 !== false)
455 $msg .= $msg2;
456 $msg .= "\n";
457 }
458
459 $msg .= "\n*** Credits: ***\n " . implode("\n ", $this->getCredits()) . "\n";
460
461
462 return $msg;
463 }
464
465 public static function makeHelpMsgHeader($module, $paramName) {
466 $modulePrefix = $module->getModulePrefix();
467 if (!empty($modulePrefix))
468 $modulePrefix = "($modulePrefix) ";
469
470 return "* $paramName={$module->getModuleName()} $modulePrefix*";
471 }
472
473 private $mIsBot = null;
474 private $mIsSysop = null;
475 private $mCanApiHighLimits = null;
476
477 /**
478 * Returns true if the currently logged in user is a bot, false otherwise
479 * OBSOLETE, use canApiHighLimits() instead
480 */
481 public function isBot() {
482 if (!isset ($this->mIsBot)) {
483 global $wgUser;
484 $this->mIsBot = $wgUser->isAllowed('bot');
485 }
486 return $this->mIsBot;
487 }
488
489 /**
490 * Similar to isBot(), this method returns true if the logged in user is
491 * a sysop, and false if not.
492 * OBSOLETE, use canApiHighLimits() instead
493 */
494 public function isSysop() {
495 if (!isset ($this->mIsSysop)) {
496 global $wgUser;
497 $this->mIsSysop = in_array( 'sysop', $wgUser->getGroups());
498 }
499
500 return $this->mIsSysop;
501 }
502
503 public function canApiHighLimits() {
504 if (!isset($this->mCanApiHighLimits)) {
505 global $wgUser;
506 $this->mCanApiHighLimits = $wgUser->isAllowed('apihighlimits');
507 }
508
509 return $this->mCanApiHighLimits;
510 }
511
512 public function getShowVersions() {
513 return $this->mShowVersions;
514 }
515
516 /**
517 * Returns the version information of this file, plus it includes
518 * the versions for all files that are not callable proper API modules
519 */
520 public function getVersion() {
521 $vers = array ();
522 $vers[] = 'MediaWiki ' . SpecialVersion::getVersion();
523 $vers[] = __CLASS__ . ': $Id$';
524 $vers[] = ApiBase :: getBaseVersion();
525 $vers[] = ApiFormatBase :: getBaseVersion();
526 $vers[] = ApiQueryBase :: getBaseVersion();
527 $vers[] = ApiFormatFeedWrapper :: getVersion(); // not accessible with format=xxx
528 return $vers;
529 }
530
531 /**
532 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
533 * classes who wish to add their own modules to their lexicon or override the
534 * behavior of inherent ones.
535 *
536 * @access protected
537 * @param $mdlName String The identifier for this module.
538 * @param $mdlClass String The class where this module is implemented.
539 */
540 protected function addModule( $mdlName, $mdlClass ) {
541 $this->mModules[$mdlName] = $mdlClass;
542 }
543
544 /**
545 * Add or overwrite an output format for this ApiMain. Intended for use by extending
546 * classes who wish to add to or modify current formatters.
547 *
548 * @access protected
549 * @param $fmtName The identifier for this format.
550 * @param $fmtClass The class implementing this format.
551 */
552 protected function addFormat( $fmtName, $fmtClass ) {
553 $this->mFormats[$fmtName] = $fmtClass;
554 }
555 }
556
557 /**
558 * This exception will be thrown when dieUsage is called to stop module execution.
559 * The exception handling code will print a help screen explaining how this API may be used.
560 *
561 * @addtogroup API
562 */
563 class UsageException extends Exception {
564
565 private $mCodestr;
566
567 public function __construct($message, $codestr, $code = 0) {
568 parent :: __construct($message, $code);
569 $this->mCodestr = $codestr;
570 }
571 public function getCodeString() {
572 return $this->mCodestr;
573 }
574 public function __toString() {
575 return "{$this->getCodeString()}: {$this->getMessage()}";
576 }
577 }
578
579