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