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