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