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