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