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