(bug 14402) Added smaxage parameter to api.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 * @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 # Nobody called setCacheMaxAge(), use the smaxage parameter
266 $this->mSquidMaxage = $params['smaxage'];
267
268 // Set the cache expiration at the last moment, as any errors may change the expiration.
269 // if $this->mSquidMaxage == 0, the expiry time is set to the first second of unix epoch
270 $expires = $this->mSquidMaxage == 0 ? 1 : time() + $this->mSquidMaxage;
271 header('Expires: ' . wfTimestamp(TS_RFC2822, $expires));
272 header('Cache-Control: s-maxage=' . $this->mSquidMaxage . ', must-revalidate, max-age=0');
273
274 if($this->mPrinter->getIsHtml())
275 echo wfReportTime();
276
277 ob_end_flush();
278 }
279
280 /**
281 * Replace the result data with the information about an exception.
282 * Returns the error code
283 */
284 protected function substituteResultWithError($e) {
285
286 // Printer may not be initialized if the extractRequestParams() fails for the main module
287 if (!isset ($this->mPrinter)) {
288 // The printer has not been created yet. Try to manually get formatter value.
289 $value = $this->getRequest()->getVal('format', self::API_DEFAULT_FORMAT);
290 if (!in_array($value, $this->mFormatNames))
291 $value = self::API_DEFAULT_FORMAT;
292
293 $this->mPrinter = $this->createPrinterByName($value);
294 if ($this->mPrinter->getNeedsRawData())
295 $this->getResult()->setRawMode();
296 }
297
298 if ($e instanceof UsageException) {
299 //
300 // User entered incorrect parameters - print usage screen
301 //
302 $errMessage = array (
303 'code' => $e->getCodeString(),
304 'info' => $e->getMessage());
305
306 // Only print the help message when this is for the developer, not runtime
307 if ($this->mPrinter->getIsHtml() || $this->mAction == 'help')
308 ApiResult :: setContent($errMessage, $this->makeHelpMsg());
309
310 } else {
311 //
312 // Something is seriously wrong
313 //
314 $errMessage = array (
315 'code' => 'internal_api_error_'. get_class($e),
316 'info' => "Exception Caught: {$e->getMessage()}"
317 );
318 ApiResult :: setContent($errMessage, "\n\n{$e->getTraceAsString()}\n\n");
319 }
320
321 $this->getResult()->reset();
322 $this->getResult()->addValue(null, 'error', $errMessage);
323
324 return $errMessage['code'];
325 }
326
327 /**
328 * Execute the actual module, without any error handling
329 */
330 protected function executeAction() {
331
332 $params = $this->extractRequestParams();
333
334 $this->mShowVersions = $params['version'];
335 $this->mAction = $params['action'];
336
337 // Instantiate the module requested by the user
338 $module = new $this->mModules[$this->mAction] ($this, $this->mAction);
339
340 if( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) {
341 // Check for maxlag
342 global $wgShowHostnames;
343 $maxLag = $params['maxlag'];
344 list( $host, $lag ) = wfGetLB()->getMaxLag();
345 if ( $lag > $maxLag ) {
346 if( $wgShowHostnames ) {
347 ApiBase :: dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' );
348 } else {
349 ApiBase :: dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' );
350 }
351 return;
352 }
353 }
354
355 if (!$this->mInternalMode) {
356 // Ignore mustBePosted() for internal calls
357 if($module->mustBePosted() && !$this->mRequest->wasPosted())
358 $this->dieUsage("The {$this->mAction} module requires a POST request", 'mustbeposted');
359
360 // See if custom printer is used
361 $this->mPrinter = $module->getCustomPrinter();
362 if (is_null($this->mPrinter)) {
363 // Create an appropriate printer
364 $this->mPrinter = $this->createPrinterByName($params['format']);
365 }
366
367 if ($this->mPrinter->getNeedsRawData())
368 $this->getResult()->setRawMode();
369 }
370
371 // Execute
372 $module->profileIn();
373 $module->execute();
374 $module->profileOut();
375
376 if (!$this->mInternalMode) {
377 // Print result data
378 $this->printResult(false);
379 }
380 }
381
382 /**
383 * Print results using the current printer
384 */
385 protected function printResult($isError) {
386 $printer = $this->mPrinter;
387 $printer->profileIn();
388
389 /* If the help message is requested in the default (xmlfm) format,
390 * tell the printer not to escape ampersands so that our links do
391 * not break. */
392 $printer->setUnescapeAmps ( ( $this->mAction == 'help' || $isError )
393 && $this->getParameter('format') == ApiMain::API_DEFAULT_FORMAT );
394
395 $printer->initPrinter($isError);
396
397 $printer->execute();
398 $printer->closePrinter();
399 $printer->profileOut();
400 }
401
402 /**
403 * See ApiBase for description.
404 */
405 public function getAllowedParams() {
406 return array (
407 'format' => array (
408 ApiBase :: PARAM_DFLT => ApiMain :: API_DEFAULT_FORMAT,
409 ApiBase :: PARAM_TYPE => $this->mFormatNames
410 ),
411 'action' => array (
412 ApiBase :: PARAM_DFLT => 'help',
413 ApiBase :: PARAM_TYPE => $this->mModuleNames
414 ),
415 'version' => false,
416 'maxlag' => array (
417 ApiBase :: PARAM_TYPE => 'integer'
418 ),
419 'smaxage' => array (
420 ApiBase :: PARAM_TYPE => 'integer',
421 ApiBase :: PARAM_DFLT => 0
422 ),
423 );
424 }
425
426 /**
427 * See ApiBase for description.
428 */
429 public function getParamDescription() {
430 return array (
431 'format' => 'The format of the output',
432 'action' => 'What action you would like to perform',
433 'version' => 'When showing help, include version for each module',
434 'maxlag' => 'Maximum lag',
435 'smaxage' => 'Cache the result for this many seconds. Errors are never cached',
436 );
437 }
438
439 /**
440 * See ApiBase for description.
441 */
442 public function getDescription() {
443 return array (
444 '',
445 '',
446 '******************************************************************',
447 '** **',
448 '** This is an auto-generated MediaWiki API documentation page **',
449 '** **',
450 '** Documentation and Examples: **',
451 '** http://www.mediawiki.org/wiki/API **',
452 '** **',
453 '******************************************************************',
454 '',
455 'Status: All features shown on this page should be working, but the API',
456 ' is still in active development, and may change at any time.',
457 ' Make sure to monitor our mailing list for any updates.',
458 '',
459 'Documentation: http://www.mediawiki.org/wiki/API',
460 'Mailing list: http://lists.wikimedia.org/mailman/listinfo/mediawiki-api',
461 'Bugs & Requests: http://bugzilla.wikimedia.org/buglist.cgi?component=API&bug_status=NEW&bug_status=ASSIGNED&bug_status=REOPENED&order=bugs.delta_ts',
462 '',
463 '',
464 '',
465 '',
466 '',
467 );
468 }
469
470 /**
471 * Returns an array of strings with credits for the API
472 */
473 protected function getCredits() {
474 return array(
475 'API developers:',
476 ' Roan Kattouw <Firstname>.<Lastname>@home.nl (lead developer Sep 2007-present)',
477 ' Victor Vasiliev - vasilvv at gee mail dot com',
478 ' Yuri Astrakhan <Firstname><Lastname>@gmail.com (creator, lead developer Sep 2006-Sep 2007)',
479 '',
480 'Please send your comments, suggestions and questions to mediawiki-api@lists.wikimedia.org',
481 'or file a bug report at http://bugzilla.wikimedia.org/'
482 );
483 }
484
485 /**
486 * Override the parent to generate help messages for all available modules.
487 */
488 public function makeHelpMsg() {
489
490 $this->mPrinter->setHelp();
491
492 // Use parent to make default message for the main module
493 $msg = parent :: makeHelpMsg();
494
495 $astriks = str_repeat('*** ', 10);
496 $msg .= "\n\n$astriks Modules $astriks\n\n";
497 foreach( $this->mModules as $moduleName => $unused ) {
498 $module = new $this->mModules[$moduleName] ($this, $moduleName);
499 $msg .= self::makeHelpMsgHeader($module, 'action');
500 $msg2 = $module->makeHelpMsg();
501 if ($msg2 !== false)
502 $msg .= $msg2;
503 $msg .= "\n";
504 }
505
506 $msg .= "\n$astriks Formats $astriks\n\n";
507 foreach( $this->mFormats as $formatName => $unused ) {
508 $module = $this->createPrinterByName($formatName);
509 $msg .= self::makeHelpMsgHeader($module, 'format');
510 $msg2 = $module->makeHelpMsg();
511 if ($msg2 !== false)
512 $msg .= $msg2;
513 $msg .= "\n";
514 }
515
516 $msg .= "\n*** Credits: ***\n " . implode("\n ", $this->getCredits()) . "\n";
517
518
519 return $msg;
520 }
521
522 public static function makeHelpMsgHeader($module, $paramName) {
523 $modulePrefix = $module->getModulePrefix();
524 if (!empty($modulePrefix))
525 $modulePrefix = "($modulePrefix) ";
526
527 return "* $paramName={$module->getModuleName()} $modulePrefix*";
528 }
529
530 private $mIsBot = null;
531 private $mIsSysop = null;
532 private $mCanApiHighLimits = null;
533
534 /**
535 * Returns true if the currently logged in user is a bot, false otherwise
536 * OBSOLETE, use canApiHighLimits() instead
537 */
538 public function isBot() {
539 if (!isset ($this->mIsBot)) {
540 global $wgUser;
541 $this->mIsBot = $wgUser->isAllowed('bot');
542 }
543 return $this->mIsBot;
544 }
545
546 /**
547 * Similar to isBot(), this method returns true if the logged in user is
548 * a sysop, and false if not.
549 * OBSOLETE, use canApiHighLimits() instead
550 */
551 public function isSysop() {
552 if (!isset ($this->mIsSysop)) {
553 global $wgUser;
554 $this->mIsSysop = in_array( 'sysop', $wgUser->getGroups());
555 }
556
557 return $this->mIsSysop;
558 }
559
560 /**
561 * Check whether the current user is allowed to use high limits
562 * @return bool
563 */
564 public function canApiHighLimits() {
565 if (!isset($this->mCanApiHighLimits)) {
566 global $wgUser;
567 $this->mCanApiHighLimits = $wgUser->isAllowed('apihighlimits');
568 }
569
570 return $this->mCanApiHighLimits;
571 }
572
573 /**
574 * Check whether the user wants us to show version information in the API help
575 * @return bool
576 */
577 public function getShowVersions() {
578 return $this->mShowVersions;
579 }
580
581 /**
582 * Returns the version information of this file, plus it includes
583 * the versions for all files that are not callable proper API modules
584 */
585 public function getVersion() {
586 $vers = array ();
587 $vers[] = 'MediaWiki ' . SpecialVersion::getVersion();
588 $vers[] = __CLASS__ . ': $Id$';
589 $vers[] = ApiBase :: getBaseVersion();
590 $vers[] = ApiFormatBase :: getBaseVersion();
591 $vers[] = ApiQueryBase :: getBaseVersion();
592 $vers[] = ApiFormatFeedWrapper :: getVersion(); // not accessible with format=xxx
593 return $vers;
594 }
595
596 /**
597 * Add or overwrite a module in this ApiMain instance. Intended for use by extending
598 * classes who wish to add their own modules to their lexicon or override the
599 * behavior of inherent ones.
600 *
601 * @access protected
602 * @param $mdlName String The identifier for this module.
603 * @param $mdlClass String The class where this module is implemented.
604 */
605 protected function addModule( $mdlName, $mdlClass ) {
606 $this->mModules[$mdlName] = $mdlClass;
607 }
608
609 /**
610 * Add or overwrite an output format for this ApiMain. Intended for use by extending
611 * classes who wish to add to or modify current formatters.
612 *
613 * @access protected
614 * @param $fmtName The identifier for this format.
615 * @param $fmtClass The class implementing this format.
616 */
617 protected function addFormat( $fmtName, $fmtClass ) {
618 $this->mFormats[$fmtName] = $fmtClass;
619 }
620
621 /**
622 * Get the array mapping module names to class names
623 */
624 function getModules() {
625 return $this->mModules;
626 }
627 }
628
629 /**
630 * This exception will be thrown when dieUsage is called to stop module execution.
631 * The exception handling code will print a help screen explaining how this API may be used.
632 *
633 * @ingroup API
634 */
635 class UsageException extends Exception {
636
637 private $mCodestr;
638
639 public function __construct($message, $codestr, $code = 0) {
640 parent :: __construct($message, $code);
641 $this->mCodestr = $codestr;
642 }
643 public function getCodeString() {
644 return $this->mCodestr;
645 }
646 public function __toString() {
647 return "{$this->getCodeString()}: {$this->getMessage()}";
648 }
649 }