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