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