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