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