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