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